I coded a class, where I declare a Light as an attribute. In the constructor I instantiate the Light object before using it, but I got the null reference exception at the line after the instantiation (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;
}
}
Thank you for your help
A Light
is a Component
, so it should exist within a GameObject
.
Have a look at this example from the 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);
}
}
Try this approach, or try adding your NodeLight
as a Component
of a GameObject
, and then changing its position, rather than the individual Light
component's.