NullReferenceException:对象引用未设置为对象 Player.AnimatePlayer () 的实例位于 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

        }
    }
}

错误是统一出现的

NullReferenceException: 未将对象引用设置为对象的实例 Player.AnimatePlayer () (在 Assets/scripts/Player.cs:53) Player.Update ()(在 Assets/scripts/Player.cs:34)*/

解决方法

唤醒函数大写:

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