实例化轻型游戏对象后出现空引用异常

时间:2016-01-07 16:15:13

标签: unity3d nullreferenceexception unityscript

我编写了一个类,我将一个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;
     }
 }

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

LightComponent,因此它应该存在于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添加为Component的{​​{1}},然后更改其位置,而不是单个GameObject组件&#39;第