【发布时间】: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);
【问题讨论】:
-
仅供参考,如果您去观看 tutorial series on Unity's website 而不是在 YouTube 上观看,则每个页面底部都有视频中编写的代码,因此您可以检查您的工作。
-
rb是一个私有字段,显然没有实例化。为什么您希望它在调用时不会抛出NullReferenceException?
标签: c# unity3d nullreferenceexception