Search code examples
c#unity-game-enginegame-engine

NullReferenceException: Object reference not set to an instance of an object Player.AnimatePlayer () (at Assets/scripts/Player.cs:53) Player.Update


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player: MonoBehaviour
{
    [SerializeField]
    private float moveForce = 1f;
    [SerializeField]
    private float jumpForce = 11f;
    private float movementx;
    private Rigidbody2D myBody;
    private SpriteRenderer sr;
    private Animator anim;
    private string WALK_ANIMATION = "walk";
    // Start is called before the first frame update
   
    private void awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();

    }
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        PlayerMoveKeyboard();
        AnimatePlayer();  // error is coming in this line
//when i am trying call this function above it is showing error which i have written down
    }
    void PlayerMoveKeyboard ()
    {
        movementx = Input.GetAxisRaw("Horizontal");
        transform.position += new Vector3(movementx, 0f, 0f) * moveForce*Time.deltaTime;
      
    }
    void AnimatePlayer()
    {
        if(movementx>0)
        {
            anim.SetBool(WALK_ANIMATION, true);
        }
        else if(movementx<0)
        {
            anim.SetBool(WALK_ANIMATION, true);

        }
        else
        {
            anim.SetBool(WALK_ANIMATION, false); // error is coming in this line

        }
    }
}

The error is coming this in unity

NullReferenceException: Object reference not set to an instance of an object Player.AnimatePlayer () (at Assets/scripts/Player.cs:53) Player.Update () (at Assets/scripts/Player.cs:34)*/


Solution

  • Capitalize the Awake function:

    private void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        anim = GetComponent<Animator>();
    }