Unity:使用 javascript 获取 NullReferenceException

Unity: getting NullReferenceException using javascript

我是 Unity 的新手,我正在关注 first Unity tutorial。当我尝试 运行 我的第一个脚本时出现此错误:

NullReferenceException: Object reference not set to an instance of an object

这是我的脚本:

#pragma strict
private var rb:Rigidbody;
private var player:GameObject;

function start() {
    player = GameObject.Find("Player");
    rb = player.GetComponent(Rigidbody);
}

function FixedUpdate() {
    var moveHorizontal:float = Input.GetAxis("Horizontal");
    var moveVertical:float = Input.GetAxis("Vertical");

    var movement:Vector3 = new Vector3(moveHorizontal , 0.0f , moveVertical);
    rb.AddForce(movement);
}

我不知道我做错了什么。

更新:

这是我的场景:

更新: 我在两个函数中都添加了 print,但似乎 start 根本没有被调用,这就是我的变量没有被初始化的原因。有什么想法吗?

您的游戏对象似乎没有附加 Rigidbody 组件并且变量 rbrb = GetComponent(Rigidbody);

之后为 null

我会删除声明

private var rb:Rigidbody;

因为您的脚本似乎正在尝试访问已声明的刚体(该刚体仍未初始化,因此为空),而不是对象的真实刚体。

旁注:看来,从 Unity 5.3.3 开始,您必须这样做:

player.GetComponent.<Rigidbody>(); 

(来自 here

您应该利用 "Unity way" 来引用变量。我的意思是,您的播放器和 rb 属性必须是 public,您只需将游戏对象从层次结构拖到检查器上的属性中即可。

如果您仍然想将其私有化,出于某种充分的理由,只需将 player = GameObject.Find("Player"); 更改为 player = GameObject.FindWithTag("Player");,您的空引用可能会得到解决。

几个小时后,我终于明白了。问题是 start 函数应该是大写的 Start。由于它是小写字母,因此未被调用并且 rb 未被初始化。

这是最终脚本:

#pragma strict
private var rb:Rigidbody;


function Start() {
    rb = GetComponent(Rigidbody);
}

function FixedUpdate() {
    var moveHorizontal:float = Input.GetAxis("Horizontal");
    var moveVertical:float = Input.GetAxis("Vertical");

    var movement:Vector3 = new Vector3(moveHorizontal , 0.0f , moveVertical);
    rb.AddForce(movement);
}