How to delay a method in Unity and C#?

unity invoke
waitforseconds - unity
unity delay without coroutine
ienumerator unity
unity c# delay in update
unity do after 5 seconds
delay in unity code
unity wait 3 seconds

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;
        }
    }
}

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);
        }
    }
}

Delay function in C#, . This will cause execution to be paused and then resumed after the specified time without blocking the current thread. This blog demonstrates creating and calling methods in Unity. Prerequisites. Unity Environment version5.6.1. Once again, refer to my previous article to get started. Scripting with C# in Unity; Creating and calling methods (Functions) Step 1. First, you have to open the Unity project. Create terrain, trees, and water. Add skyboxes in your project.

This can be done in a number of ways. Before showing you the specific stuff, here is a basic structure, common to all example's codes, that I'll be using:

public class ColorChanger : MonoBehaviour {
    //Avoid Find and GetComponent methods in performance-critical contexts like Update and FixedUpdate
    //Store the value once in the beginning. This is called 'caching'
    public SpriteRenderer _renderer;

    //Don't hard-code stuff like this
    public Color[] _colors;

    public float _colorChangeInterval = 0.5f;

    //Convenience property to access _renderer.color
    public Color Color {
        get => _renderer.color;
        set => _renderer.color = value;
    }

    private void Start() {
        //Attempts to find the SpriteRenderer in the object if it wasn't set in the inspector
        if (!_renderer)
            _renderer = GetComponent<SpriteRenderer>();
    }

    //This piece of code does a specific thing, so it's best to put it in a method
    public void ChangeColor() {
        if (_colors.Length < 1)
            Debug.LogError($"You forgot to set {nameof(_colors)} in the Inspector. Shame! Shame!");
        Color = _colors[Random.Range(0, _colors.Length - 1)];
    }
}

Here are some of the main, in order of how intuitive they are, in my opinion:


Timer pattern:

Two flavours for this.

1) Can be an accumulator for elapsed time (as in the code below), or the reverse, and decrement from interval to zero:

private float _elapsed;

private void Update() {
    _elapsed += Time.deltaTime;

    if (_elapsed < _colorChangeInterval)
        return;
    ChangeColor();
    _elapsed %= _colorChangeInterval;
}

Or 2) Can be a timestamp-check trigger from last, or until next (as below), timestamp:

//Replaces _elapsed
private float _timestamp;

private void Start() {
    //...
    _timestamp = Time.time; //Initial timestamp
}

private void Update() {
    if (Time.time < _timestamp + _colorChangeInterval)
        return;
    ChangeColor();
    _timestamp = Time.time;
}

Coroutine & WaitForSeconds:

This is the recommended procedure for when you need to delay or sequence code in unity.

Note that there are other types of wait methods provided by unity, like WaitWhile, WaitUntil, etc...

//Since unlike code in Update, coroutines need to be started and stopped, we start it when the script is enabled
private void OnEnable() {
    StartCoroutine(ChangeColorContinuously());
}

//This is automatically stopped by unity when the script is disabled
private IEnumerator ChangeColorContinuously() {
    while (true) {
        yield return new WaitForSeconds(_colorChangeInterval);
        ChangeColor();
    }
}

Don't do Async Await!

Well, it can be done, but it has a lot of pitfalls and is very much NOT recommended for beginners.

And it's not intended to replace Coroutines anyways.


Don't do InvokeRepeating!

It's a method that relies on magic strings and reflection. Useful for quick & easy setups for example code, but that if at all possible (and it is possible, thanks to methods above) should be avoided like the plague in production code.

How make the script wait/sleep in a simple way in unity, before calling that function to its second parameter. The example below will call the feedDog() function after 5 seconds the Invoke is called. Unity 2017.1 C# Waiting or delaying a function during Switch, and repeating a function with delay.

You can use time counter and Time.deltaTime:

public class colorchange : MonoBehaviour
{
    public int color;
    public bool stop = true;
    public float delay;
    private float timer;
    void Start()
    {
        timer = delay;
    }

    void Update()
    {
        timer -= Time.deltaTime;
        if (timer <= 0) {
            timer = delay;
            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;
            }
        }
    }
}

How to delay a method in Unity and C#?, You can put your code in a loop in a Coroutine that iterates once every number of seconds: public class colorchange : MonoBehaviour { public  To do repeating calls use “InvokeRepeating” and add an additional parameter to set the delay between each call. InvokeRepeating("launchRocket", 4, 0.5); // triggers after 4 seconds and does another calls every 0.5 seconds

You can handle this with a simple coroutine. If you dont know how, take a look at this link ( https://docs.unity3d.com/ScriptReference/WaitForSeconds.html ) on Unity's official API documentation.

If you dont want to work with coroutines, you can use Unity's InvokeRepating method. Create a new function for changing the color and Invoke it every x amount of seconds. Here's the link for InvokeRepating method too https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html

ps: In this case using Switch for determining the color integer is more efficient rather using if and else if for each color code. Its more efficient and easier to scale up.

Scripting API: WaitForSeconds, IEnumerator ExampleCoroutine() { //Print the time of when the function is first called. Debug.Log("Started Coroutine at timestamp : " + Time.time); //yield on a new  Suspends the coroutine execution for the given amount of seconds using scaled time. The real time suspended is equal to the given time divided by Time.timeScale. See WaitForSecondsRealtime if you wish to wait using unscaled time. WaitForSeconds can only be used with a yield statement in coroutines.

Another alternatively to Coroutines or a simple timer in Update would be to use InvokeRepeating and stop it using CancelInvoke. In such a use case as yours I find this way easier to implement and control:

public float Interval = 1;

[SerializeField] private SpriteRenderer spriteRenderer;

private void Awake()
{
    // DO THIS ONLY ONCE
    if(!spriteRenderer) spriteRenderer = GetComponent<SpriteRenderer>();
}

// Automatically called when this component or GameObject gets enabled
private void OnEnable ()
{
    // Start invoking every Interval seconds
    InvokeRepeating(nameof(ChangeColor), Interval, Interval);
}

// Automatically called when this component or GameObject gets disabled
private void OnDisable()
{
    // Stop the repeated invoking 
    CancelInvoke();
}

private void ChangeColor()
{
    Debug.Log("Hello");
    color = Random.Range(1, 5);

    // You should also use a switch case here
    switch(color)
    {
        case 2:
            spriteRenderer.color = Color.blue;
            break;

        case 3:
            spriteRenderer.color = Color.red;
            break;

        case 4:
             spriteRenderer.color = Color.yellow;
             break;
    }
}

Then you could simply enable and disable the color changing by enabling and disabling this component.

Or alternatively simply move the according code lines from OnEnable and OnDisable to according public methods like public void StartColorChange and public void StopColorChange.

Do After Time, Do After Time - Creating Delays in Unity | Unity Do Something After Time Tutorial UNITY 2017 Duration: 3:35 Posted: Mar 12, 2018 Unity3D How To Delay Code Execution. In a game that I am developing, I needed a slight but simple delay of code execution in order to allow the enemy death animation to complete. Here is the method that I used: Of the different methods to add a delay to executing code, the easiest and less complicated that I’ve found is to use the Invoke method.

Unity3D How to : Delay Method with Invoke(), Unity3D How to : Delay Method with Invoke(). UnityBeginner UNITY 2017 -Call Method From Duration: 2:09 Posted: Oct 24, 2014 If time is set to 0, the method is invoked at the next Update cycle. In this case, it's better to call the function directly. For better performance and maintability, use Coroutines instead.

In Unity, how do I set up a delay before an action?, You could create a variable for example called timer of type float and make it equal to the amount of seconds you would like to wait, then in the Update() function 

How to Teach the Method of Unity , be explained in the working out of these simple problems , but it is better to delay If children cannot do this well , the “ Method of Unity , " instead of simplifying the when the foregoing suggestions for statement , & c . , are applied to them .

Comments
  • Count the amount of time since the last execution (e.g.: using Time.deltaTime) and only change color when it surpasses a certain amount
  • OP, if you want to provide your own answer, please do so as an answer rather than an edit to the question. Edit rolled back.
  • do u maybe know how to stop the color change if I put onmousedown()
  • @LaurenzKaml I edited the answer to include a toggle function in OnMouseDown() Just be sure to have a Collider or GUIElement attached to the same gameobject as the script.
  • You could then actually directly make Start an IEnumerator ;) and remove an empty Update method .. unity invokes it via message which only causes unnecessary overhead
  • sorry Ruzihm but I just started unity 1 day ago and nearly don't know anything could u show me how.
  • One suggestion, create a single WaitUntil object and yield return it, instead of new WaitUntil every time.