【问题标题】:Why am I getting a Null Reference Exception when there is clearly a proper reference? (Unity)当有明确的参考时,为什么我会收到空​​参考异常? (统一)
【发布时间】:2017-04-26 00:52:31
【问题描述】:

我是 Unity 新手,我有一小段代码实际上是直接从 Unity 教程中获取的。教程可以在这里找到,大约 12:46
https://www.youtube.com/watch?v=7C7WWxUxPZE

脚本已正确附加到游戏对象,并且游戏对象具有刚体组件。

本教程已经有几年的历史了,但我在 API 中查找了一些东西,就这段特定的代码而言,一切似乎都是一样的。

这是脚本:

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

public class PlayerController : MonoBehaviour {
private Rigidbody rb;

void Start()
    {
    rb.GetComponent <Rigidbody> ();

    }


void FixedUpdate() 
    {

    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);    

    rb.AddForce (movement);
    }
}

我在两个地点获得 NRE:

rb.GetComponent <Rigidbody> ();

rb.AddForce (movement);

【问题讨论】:

标签: c# unity3d nullreferenceexception


【解决方案1】:

您不应该在 rb 对象上调用 GetComponent。您应该在 MonoBehaviour 类本身上调用 GetComponent。然后,您需要获取该调用的结果并将其分配给 rb

void Start()
{
    rb = GetComponent <Rigidbody> ();
}

如果修复此问题后,您仍然在 rb.AddForce (movement); 调用中获得 NRE,这意味着脚本附加到的游戏对象没有附加 Rigidbody,您需要确保向对象添加一个也。

要超出本教程的内容,您可能想做的一件事是将RequireComponent 属性放在MonoBehavior 类上,这样脚本会自动将Rigidbody 添加到游戏对象(如果还没有的话)存在。

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

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {
private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();

    }


    void FixedUpdate() 
    {

        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);    

        rb.AddForce (movement);
    }
}

【讨论】:

  • 现在说得通了……非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 2016-08-08
  • 2021-04-01
  • 2018-11-16
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 2020-01-01
相关资源
最近更新 更多