Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading