【发布时间】:2025-11-26 14:35:01
【问题描述】:
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)*/
【问题讨论】:
-
好吧,你的
awake方法被调用了吗?如果是,GetComponent<Animator>是否返回非空值?请注意,您不应该只解释您预期会发生什么,而是您已经证明正在通过调试器或日志记录发生。 -
我同意 Jon Skeet 的观点。尝试在 Update 上记录
anim的值以查看它返回的内容。如果它返回null,那么由于某种原因,anim没有设置为您的GetComponent<>()。这可能是因为两个原因:Awake()未被调用,或者因为您可能没有附加到 GameObject 的 Animator 组件。 -
@JonSkeet 先生,我叫醒了,但它不工作,GetComp 已经在那里.. 它不工作(非常感谢你的帮助)
-
@undevable 先生实际上我是新手,你在最后一个动画师说的可能没有附加我不明白,但我已经附加了动画控制器......(谢谢非常有帮助)
-
在哪里你给
awake()打过电话?您的代码中没有任何迹象。 “它不起作用”真的不能告诉我们太多。
标签: c# unity3d game-engine