Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Reverend-Speed · Jan 15, 2015 at 12:57 AM · coroutinetimerloopwaitforsecondsrepeating

How to make WaitForSeconds work as a repeating/looping timer?

Hey folks. WaitForSeconds is bugging me again... I'm currently making a object pool that repopulates (re-enables) deactivated game objects every second or so.

Normally I'd use something like,

 public     float timerLimit = 1.0f;
 private    float timer = 0.0f;
 
 void Update () {
 
     timer += time.deltatime;
     if(timer >= 1.0f){
         Debug.Log("Do stuff to populate level!");
         timer = 0.0f;
     }
 }

...but I'm trying to break some old habits and use coroutines instead (I've been warned off using Invoke, as coroutines are more flexible).

However, upon using,

     public    float    populationRate    = 1.0f;
 
         // Update is called once per frame
     void Update () {
     
 
         StartCoroutine(SpawnLoop());
 
     }
 
     IEnumerator SpawnLoop () {
 
     yield return new WaitForSeconds (populationRate);
 
     Debug.Log ("Waited for " + populationRate + " seconds, and it's now " + Time.time);
 
     }

...and expecting a log like,

 Waited for 3 seconds, and it's now 3.000000
 Waited for 3 seconds, and it's now 6.000000
 Waited for 3 seconds, and it's now 9.000000
 Waited for 3 seconds, and it's now 12.000000
 Waited for 3 seconds, and it's now 15.000000

...instead, I get a log like:

 Waited for 3 seconds, and it's now 3.001297
 Waited for 3 seconds, and it's now 3.072943
 Waited for 3 seconds, and it's now 3.358437
 Waited for 3 seconds, and it's now 3.466427
 Waited for 3 seconds, and it's now 3.497489

My intent was to create a passive loop to check my current population and then do stuff - instead of actively consuming CPU time each Update (trust me, this isn't a premature optimisation).

Is WaitForSeconds unsuitable for this? Is there a way to make it loop?

If I use a 'while = true' or 'for' loop in the coroutine, isn't this basically the same as just sticking that code into Update and building a short timer?

Questions, Unity community! Questions! Do you have... answers?!?!

Many thanks in advance,

--Rev

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Simon-Larsen · Jan 15, 2015 at 01:19 AM 2
Share

I'm unsure if a lot of CPU time is used when waiting inside a loop inside a coroutine, but my guess is that it won't use much. I'd move your IEnumerator code inside a while=true loop and call it from the Awake() method ins$$anonymous$$d of Update() - calling it from update will just queue up a whole bunch of spawns waiting for 'populationRate' time to pass.

 IEnumerator SpawnLoop () 
 {
     while(true)
     {
         yield return new WaitForSeconds (populationRate);
  
         Debug.Log ("Waited for " + populationRate + " seconds, and it's now " + Time.time);
     }
 }
avatar image iwaldrop · Jan 15, 2015 at 01:21 AM 0
Share

Why didn't you just answer the question, @Simon Larsen? :)

avatar image Reverend-Speed · Jan 15, 2015 at 10:06 AM 0
Share

Thanks for pointing out the Update issue, Simon! Should have known better, but obviously didn't! Cheers!

1 Reply

· Add your reply
  • Sort: 
avatar image
9
Best Answer

Answer by iwaldrop · Jan 15, 2015 at 01:17 AM

You need to remember that in coroutines you are responsible for setting up a loop and ending it.

 IEnumerator SpawnLoop()
 {
     while (enabled)
     {
         yield return new WaitForSeconds (populationRate);
         Debug.Log ("Waited for " + populationRate + " seconds, and it's now " + Time.time);
     }
 }

The above code will stop executing when the MonoBehaviour is disabled.

Furthermore, you will be starting that coroutine every frame, which is a no-no, and is why you're seeing results spit out every frame after a specified wait. You have n coroutines all waiting for that time limit before spitting something out to the log. Instead, start it in one of either the Awake or Start methods.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Reverend-Speed · Jan 15, 2015 at 10:05 AM 0
Share

In retrospect, obvious. If WaitForSeconds is just the timer and not a loop, I need to implement the loop myself - hence while(enabled) (nice refinement on while(true)!).

Your - and Simon's - comments on the placement of coroutines in Update are appreciated. I knew I shouldn't do that, just forgot - and now I've a solid example of why not to do that in the future.

Cheers!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Sequentially wait for multiple coroutines to finish 0 Answers

How To Make UI Button 2 Appear Three Seconds After UI Button 1 is pressed 1 Answer

Making a timer using WaitForSecondsRealtime without keyword 'new'? 1 Answer

Looping a Script 2 Answers

WaitForSeconds bug,Coroutine Bug 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges