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 /
  • Help Room /
avatar image
2
Question by maaboo · Jan 06, 2013 at 03:58 PM · c#coroutineupdate

Execute coroutine in Update()

Hi!

I've just get into Unity and trying to write first game concept.

In the concept there are some random events generated in determined time (for example 8-12 seconds). So i try this:

     void Update()
     {
         StartCoroutine(GenerateEvent());
     }

     IEnumerator GenerateEvent()
     {
 
         // wait for 8-12 seconds
         // select new point
         // show a popup badge 
         // work with popup
 
         int _wait = Random.Range(8, 12);
         yield return new WaitForSeconds(_wait);
 
         // Below are bunch of lines i hope doesn't matter about the question
 
     }

But it doesn't work as i expect. I need to do something every X-Y seconds.

I tried to write something like:

     IEnumerator DebugEnumerator(float delay)
     {
         yield return new WaitForSeconds(delay);
         Debug.Log("Waited for: 1 second (DEBUG)");
     }

But it behaves in Update() like waits for one second and then executes every frame, not every second.

Probably i misunderstood the concept of coroutine. Can you tell me the way?

Comment
Add comment
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

8 Replies

· Add your reply
  • Sort: 
avatar image
13

Answer by LukaKotar · Jan 06, 2013 at 05:04 PM

Update() cannot be a coroutine, but you could create a while loop inside of an IEnumerator to achieve your desired behavior. Start the coroutine in Start(), and the loop will cause it to repeat once it reaches the end.

 void Start () {
     StartCoroutine(Example());
 }
 
 IEnumerator Example () {
     while(true){ // This creates a never-ending loop
         yield return new WaitForSeconds(2);
         // Do stuff here
         // If you want to stop the loop, use: break;
     }
 }
Comment
Add comment · Show 5 · 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 FallingRocketGames · Sep 29, 2017 at 03:30 PM 0
Share

If I do this solution unity crashes any thoughts?

avatar image LukaKotar · Sep 29, 2017 at 03:58 PM 0
Share

@jointothedarkside Your loop is most likely trying to run infinite times in a single frame, making your game freeze. You can do yield return null, which will make the loop wait until the next frame before continuing.

 while(true){
     // Do stuff here
     yield return null;    // Wait for the next frame before looping over
 }
avatar image FallingRocketGames LukaKotar · Sep 29, 2017 at 05:16 PM 0
Share

actually i saw this other solution where they recommended to use while(true){ // Do stuff here yield return null; // Wait for the next frame before looping over } yield return null;

And If you do so you get a warning for the second return null, I'm kind of lost here

avatar image LukaKotar FallingRocketGames · Sep 29, 2017 at 10:36 PM 1
Share

If you never stop the loop (either with the break keyword or by having the condition turn false), then all code after the loop is unreachable. I'm guessing that's why you're seeing the warning. You don't need the second yield return null.

avatar image charlenedanes · Apr 08, 2018 at 03:39 PM 0
Share

it's not working for me. it only works when i press a button to go to another scene :(

avatar image
6

Answer by AlexHogan · May 01, 2015 at 04:07 AM

Your Coroutine is fine - nice jobe. The problem is that update is sending the event every frame, so your coroutine is starting every frame.

Just change

 void Update()
      {
          StartCoroutine(GenerateEvent());
      }

to be

 void Start()
      {
          StartCoroutine(GenerateEvent());
      }

So then your event will only get fired once.

Comment
Add comment · 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
5

Answer by Owen-Reynolds · Jan 06, 2013 at 08:44 PM

If you're just starting Unity, maybe skip coroutines completely for now. The best way to do something is a way that makes sense to you. See if this seems more obvious, counting time down to 0, then resetting:

 public float secsToNext=0.0f; // public lets you check it running in the Inspector

 Update() {
   secsToNext -= Time.deltaTime;  // T.dt is secs since last update
   if(secsToNext<=0) {
     secsToNext = Random.Range(8.0f, 12.0f);
     // do thing here:
   }
   ....

A coroutine automatically does the countdown for you, so runs a little faster. But if things are allready fast enough, there's no point complicating things.

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 NoobCorpProductions · Apr 15, 2018 at 09:26 PM 0
Share

well this makes my functions do nothing, creative approach or maybe im doing something wrong

avatar image
3

Answer by Eric5h5 · Jan 06, 2013 at 05:06 PM

You should not use Update for this, since Update always runs once every frame and cannot be delayed in any way.

 IEnumerator Start () {
     yield return new WaitForSeconds (Random.Range (8, 12));
     // Do stuff
 }
Comment
Add comment · 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
1

Answer by bullze · Apr 11, 2017 at 08:41 AM

You can do it like

 bool isCoroutineReady = true;
 void Update()
 {
 
   if(isCoroutineReady)
   {
      isCoroutineReady = false;
      StartCoroutine(yourCoroutine());
   }
 
 }
 
 IEnumerator yourCoroutine()
 {
 
     //your Code
 
     isCoroutineReady = true;
     yield return null
 }

Comment
Add comment · Show 2 · 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 Bunny83 · Apr 11, 2017 at 11:50 AM 1
Share

This is not recommended as it will generate a lot of garbage since you constantly starting a new coroutine. If you want an endless running coroutine, just use a while loop like Luka$$anonymous$$otar showed in his answer.

avatar image bullze Bunny83 · Apr 11, 2017 at 12:51 PM 0
Share

good to know, thanks

  • 1
  • 2
  • ›

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

23 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

Related Questions

Coroutine is called twice less time than update 1 Answer

Custom Coroutine With Arguments 1 Answer

Good Day! I have this code but I had an error 0 Answers

Trying to move buttons via Coroutine and transform.Translate 0 Answers

Coroutine only works one way 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