Search code examples
unity-game-enginedelay

UNITY - How do I change color at a delay?


I am trying to change the background color of the Main Camera. When I put the code below, it changes the color every frame. Why does this happen? How can I fix it?

function Update () {
ChangeColor();
}

function ChangeColor() {
this.camera.backgroundColor = Color32(Random.Range(0, 255), Random.Range(0, 255), Random.Range(0, 255), 1);
yield WaitForSeconds(5);
}

Solution

  • You're looking for something called Coroutines.

    Update() is called 60 times per second. As you have ChangeColor() inside the Update() method, it will be called regardless of the yield statement within the ChangeColor() method, as yield only works from inside coroutines.

    You will need to call the method like this:

    StartCoroutine(ChangeColor()); 
    

    or

    StartCoroutine("ChangeColor"); 
    

    Be aware that if you put that line inside the Update() method you will be starting a new coroutine 60 times a second. If you want ChangeColor() to continually run after being started you'll need to change its logic slightly and place it in your Start() method, or in a place where it's called once.

        function ChangeColor() {
        while(true){
            this.camera.backgroundColor = Color32(Random.Range(0, 255), Random.Range(0, 255),     Random.Range(0, 255), 1);
            yield WaitForSeconds(5);
            }
        }
    

    You'll notice I added a while loop that is an infinite loop, and INSIDE the while loop I placed the yield statement. This will properly yield the method for 5 seconds before looping again and yielding forever.

    Some additional notes:

    • Make sure you choose the correct version of StartCoroutine(...). The one that takes a string can be stopped by using StopCoroutine("NameOfMethod"). The other one that takes the method signature itself cannot be stopped after being started.

    • Coroutines live on the gameobject script that creates them. So if your camera had the script which calls the ChangeColor() method and it was destroyed, then the ChangeColor() coroutine is also stopped and destroyed.

    Links to the other coroutine methods.

    StartCoroutine