Hi developers, I want to make a traffic light using 3 point lights that turn on and off. This is my script :
public class TrafficLight : MonoBehaviour {
public GameObject Red;
public GameObject Green;
public GameObject Yellow;
// Use this for initialization
void Start () {
//GameObject.Yellow.SetActive(false);
GameObject.FindGameObjectWithTag("_YellowLight").SetActive(false);
}
IEnumerator Example() {
GameObject.FindGameObjectWithTag("_GreenLight").SetActive(true);
GameObject.FindGameObjectWithTag("_RedLight").SetActive(false);
//GameObject.Green.SetActive(true);
//GameObject.Red.SetActive(false);
yield return new WaitForSeconds(30);
GameObject.FindGameObjectWithTag("_YellowLight").SetActive(true);
GameObject.FindGameObjectWithTag("_GreenLight").SetActive(false);
//GameObject.Yellow.SetActive(true);
//GameObject.Green.SetActive(false);
yield return new WaitForSeconds(4);
GameObject.FindGameObjectWithTag("_RedLight").SetActive(true);
GameObject.FindGameObjectWithTag("_YellowLight").SetActive(false);
//GameObject.Red.SetActive(true);
//GameObject.Yellow.SetActive(false);
yield return new WaitForSeconds (30);
}
// Update is called once per frame
void Update () {
StartCoroutine (Example());
}
}
And this is the error that I get :
NullReferenceException: Object reference not set to an instance of an object
TrafficLight+c__Iterator3.MoveNext () (at Assets/Scripts/TrafficLight.cs:20)
UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)
TrafficLight:Update() (at Assets/Scripts/TrafficLight.cs:45)
If you notice I have tried another solution which is commented out but again I get another error :
Yellow, Green, Red are not defined.
Any help?
Thanks in advance for your time
By the way, besides the logic of the lights (I haven't checked), don't start the coroutine inside Update function (as it will happen once every frame), just start it iside your Start function.
– Andres-FernandezThank you for your time. when i use Yellow.SetActive(false); i get an error Yellow is not defined which is defined as gameobject. I don't understand when an object is null. To me if the object is on the scene then it is not null ? I changed the coroutine and put it in as you suggested I was suspecting it was better put in the start()
– AfassolasFor the object not to be null, it has to be linked to the script (by dragging it in the editor, or by using the Find function). Make sure you link the objects, and post the full error, so we can figure out how to solve it.
– Andres-Fernandez