r/UnityHelp • • Aug 29 '21

Trying to understand Corutines

Shouldn't this pritnt "Text" in the console every 3 three seconds?

IEnumerator test()

{

Debug.Log("text");

yield return new WaitForSeconds(3);

}

I ofc start corutine in update.

It spams the output every frame rather than every 3 seconds

2 Upvotes

7 comments sorted by

1

u/Asylation Helped Community Aug 29 '21

https://docs.unity3d.com/ScriptReference/WaitForSeconds.html

"See WaitForSecondsRealtime if you wish to wait using unscaled time."

1

u/jollyolly2137 Aug 29 '21

well, I changed it to WaitForSecondsRealtime(3) but it still blurps out hundreds of logs a second : /

1

u/Asylation Helped Community Aug 29 '21

Pardon. I just now realized you are running the coroutine from Update(). This means it will create a new coroutine each frame. Also, this coroutine body will run the debug function, then wait 3 seconds and stop its function. There is no loop.

1

u/jollyolly2137 Aug 29 '21

Thank you for your help. Now I understand more or less whats going on in corutines

1

u/Canamla Aug 29 '21

If you want to run it from Update, check against a condition when you want to run the coroutine, make that condition false while it runs, then make the condition true at the end so it can repeat (if desired). A bool is probably the simplest.

1

u/jollyolly2137 Aug 29 '21

Yea, that was a weird and stupid mistake.

1

u/Canamla Aug 29 '21

Lol I've had my fair share of frustrations with it. Took me longer than I'd like to admit to figure out how to use them properly :p