首页 > 解决方案 > Unity:无法让动画工作,得到 NullReferenceException

问题描述

我到处寻找并尝试了一切来让我的代码工作,但我仍然无法让它工作。

如果有人可以尝试帮助我解决此问题,我将不胜感激。

//PLAYER JUMP MOVEMENT
if (onGround == true && Input.GetKey("w"))
{
    onGround = false;
    rb.velocity = new Vector2(rb.velocity.x, playerJumpSpeed * Time.deltaTime);
    isJumping = true;
}


if (playerLives <= 0)
{
    Destroy(gameObject, 5f);
}

if (isJumping == true)
{
    anim.SetBool("isJumping", true);
}

if (isJumping == false)
{
    anim.SetBool("isJumping", false);
}

出现NullReferenceException在:

anim.SetBool("isJumping", true);

anim.SetBool("isJumping", false);

标签: c#unity3danimation

解决方案


public class playerController : MonoBehaviour
{
private Animator anim;

// Start is called before the first frame update
void Start()
{
    Animator anim = GetComponent<Animator>();
}

这段代码给我错误的原因是我不应该在 Start 中将 anim 声明为 Animator。为简化起见,代码应如下所示:

public class playerController : MonoBehaviour
{
private Animator anim;

// Start is called before the first frame update
void Start()
{
   anim = GetComponent<Animator>();
}

推荐阅读