NullReferenceException:对象引用未设置为 C# 中对象的实例
NullReferenceException: Object reference not set to an instance of an object in C#
执行完代码后在代码末尾出现异常,我对代码做了很多修改,但没有任何改变。
NullReferenceException: Object reference not set to an instance of an object
RocketController.Start () (at Assets/Script/RocketController.cs:10)
这个异常的原因是什么?
using UnityEngine;
using System.Collections;
public class RocketController : MonoBehaviour {
// Use this for initialization
Rigidbody2D rd;
void Start () {
rd.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if(Input.GetKey("right"))
{
rd.velocity = new Vector2(1,0);
}
else if(Input.GetKey("left"))
{
rd.velocity = new Vector2(-1,0);
}
else
{
rd.velocity = new Vector2(0,0);
}
}//close update
}
更新: 这是工作代码:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class RocketController : MonoBehaviour {
// Use this for initialization
Rigidbody2D rd;
void Start () {
rd = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if(rd == null)
return;
if(Input.GetKey("right"))
{
rd.velocity = new Vector2(1,0);
}
else if(Input.GetKey("left"))
{
rd.velocity = new Vector2(-1,0);
}
else
{
rd.velocity = new Vector2(0,0);
}
}//close update
}
变量 rd
从未实例化,因此它为空。需要实例化才能使用
A NullReferenceException
表示您尝试使用的对象是空的。
Unity中刚体实例化方法如下:rd = GetComponent<Rigidbody2D>();
More info
执行完代码后在代码末尾出现异常,我对代码做了很多修改,但没有任何改变。
NullReferenceException: Object reference not set to an instance of an object RocketController.Start () (at Assets/Script/RocketController.cs:10)
这个异常的原因是什么?
using UnityEngine;
using System.Collections;
public class RocketController : MonoBehaviour {
// Use this for initialization
Rigidbody2D rd;
void Start () {
rd.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if(Input.GetKey("right"))
{
rd.velocity = new Vector2(1,0);
}
else if(Input.GetKey("left"))
{
rd.velocity = new Vector2(-1,0);
}
else
{
rd.velocity = new Vector2(0,0);
}
}//close update
}
更新: 这是工作代码:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody2D))]
public class RocketController : MonoBehaviour {
// Use this for initialization
Rigidbody2D rd;
void Start () {
rd = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if(rd == null)
return;
if(Input.GetKey("right"))
{
rd.velocity = new Vector2(1,0);
}
else if(Input.GetKey("left"))
{
rd.velocity = new Vector2(-1,0);
}
else
{
rd.velocity = new Vector2(0,0);
}
}//close update
}
变量 rd
从未实例化,因此它为空。需要实例化才能使用
A NullReferenceException
表示您尝试使用的对象是空的。
Unity中刚体实例化方法如下:rd = GetComponent<Rigidbody2D>();
More info