Search code examples
c#unity-game-enginedelay

How to delay a method in Unity and C#?


My name is Laurenz and my question is how to delay the color changing of my sprites in Unity with c#.

Right now I have a random generator which choses a color based on a number, but this happens every frame. So now the real challenge is how to delay it so that it changes less often.

public class colorchange : MonoBehaviour
{
    public int color;
    public bool stop = true;
    void Start()
    {

    }

    void Update()
    {

        Debug.Log("Hello");
        color = Random.Range(1, 5);
        if (color == 2)
        {
            gameObject.GetComponent<SpriteRenderer>().color = Color.blue;
        }
        if (color == 3)
        { 
            gameObject.GetComponent<SpriteRenderer>().color = Color.red;
        }
        if (color == 4)
        {
            gameObject.GetComponent<SpriteRenderer>().color = Color.yellow;
        }
    }
}

Solution

  • You can put your code in a loop in a Coroutine that iterates once every number of seconds:

    public class colorchange : MonoBehaviour
    {
        public int color;        
        public float delaySeconds = 1f;
        IEnumerator changeColorCoroutine;
    
        SpriteRenderer mySprite;
    
        public bool doChangeColor;
    
        void Start()
        {
            // cache result of expensive GetComponent call
            mySprite = GetComponent<SpriteRenderer>();
    
            // initialize flag
            doChangeColor = true;
    
            // create coroutine
            changeColorCoroutine = ChangeColor();
    
            // start coroutine
            StartCoroutine(changeColorCoroutine);
        }
    
        void OnMouseDown()
        {
            // toggle doChangeColor
            doChangeColor = !doChangeColor;
        }
    
        IEnumerator ChangeColor()
        {
            WaitUntil waitForFlag = new WaitUntil( () => doChangeColor);
    
            while (true)
            {
                yield return waitForFlag;
    
                Debug.Log("Hello");
                color = Random.Range(1, 5);
    
                // switch for neater code
                switch (color)
                {
                case 2:
                    mySprite.color = Color.blue;
                    break;
    
                case 3:
                    mySprite.color = Color.red;
                    break;
    
                case 4:
                    mySprite.color = Color.yellow;
                    break;
                }
    
                yield return new WaitForSeconds(delaySeconds);
            }
        }
    }