我编写了一个类,我将一个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;
}
}
感谢您的帮助
答案 0 :(得分:1)
Light
是Component
,因此它应该存在于GameObject
内。
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
添加为Component
的{{1}},然后更改其位置,而不是单个GameObject
组件&#39;第