How to call Coroutine every X seconds?

I’m trying to make a class that has a Coroutine run every 2 seconds. If it works, it should print to console "Ran" every 2 seconds. However, this current version just prints to console seemingly every frame. How can this be logically fixed?

public class EveryXSeconds: MonoBehaviour
{

    public bool running = true;

    private void Update()
    {
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        // Set the function as running
        running = true;

        // Do the job until running is set to false
        while (running)
        {
            // Do your code
            print("Ran");

            // wait for seconds
            yield return new WaitForSeconds(2f);
            running = false;
        }
    }
}

>Solution :

public class EveryXSeconds: MonoBehaviour{

    private void Start()
    {
        StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        while (true)
        {
            // Do your code
            print("Ran");

            // wait for seconds
            yield return new WaitForSeconds(2f);
        }
    }
}

If you write the above, it will be printed every 2 seconds.

Leave a Reply