实例化轻型游戏对象后出现空引用异常
Null reference exception after instantiating a light gameobject
我编码了一个 class,我在其中将 Light 声明为一个属性。在构造函数中,我在使用它之前实例化了 Light 对象,但是在实例化之后的行中我得到了空引用异常 (NodeLight.type = LightType.Spot;
).
using UnityEngine;
using System.Collections;
public class Node{
public bool walkable;
public Vector3 worldPosition;
public bool Selected;
public Light NodeLight;
public Node(bool _walkable, Vector3 _worldPos) {
Selected = false;
walkable = _walkable;
worldPosition = _worldPos;
NodeLight = new Light();
NodeLight.type = LightType.Spot;
NodeLight.transform.position = new Vector3(worldPosition.x, worldPosition.y + 3f, worldPosition.z);
NodeLight.enabled = false;
}
}
感谢您的帮助
一个Light
是一个Component
,所以它应该存在于一个GameObject
中。
看看这个来自 Unity Docs 的例子:
public class ExampleClass : MonoBehaviour {
void Start() {
GameObject lightGameObject = new GameObject("The Light");
Light lightComp = lightGameObject.AddComponent<Light>();
lightComp.color = Color.blue;
lightGameObject.transform.position = new Vector3(0, 5, 0);
}
}
尝试这种方法,或尝试将您的 NodeLight
添加为 GameObject
的 Component
,然后更改其位置,而不是单个 Light
组件的位置。
我编码了一个 class,我在其中将 Light 声明为一个属性。在构造函数中,我在使用它之前实例化了 Light 对象,但是在实例化之后的行中我得到了空引用异常 (NodeLight.type = LightType.Spot;
).
using UnityEngine;
using System.Collections;
public class Node{
public bool walkable;
public Vector3 worldPosition;
public bool Selected;
public Light NodeLight;
public Node(bool _walkable, Vector3 _worldPos) {
Selected = false;
walkable = _walkable;
worldPosition = _worldPos;
NodeLight = new Light();
NodeLight.type = LightType.Spot;
NodeLight.transform.position = new Vector3(worldPosition.x, worldPosition.y + 3f, worldPosition.z);
NodeLight.enabled = false;
}
}
感谢您的帮助
一个Light
是一个Component
,所以它应该存在于一个GameObject
中。
看看这个来自 Unity Docs 的例子:
public class ExampleClass : MonoBehaviour {
void Start() {
GameObject lightGameObject = new GameObject("The Light");
Light lightComp = lightGameObject.AddComponent<Light>();
lightComp.color = Color.blue;
lightGameObject.transform.position = new Vector3(0, 5, 0);
}
}
尝试这种方法,或尝试将您的 NodeLight
添加为 GameObject
的 Component
,然后更改其位置,而不是单个 Light
组件的位置。