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
0
Question by Coned_Stoding_games · Mar 09, 2014 at 11:50 PM · c#coroutines

Can't get a coroutine to work as expected.

Hi, I'm having trouble with this coroutine. Basically all I want is for my enemy to wait for 3 seconds before moving each time it moves. At present the enemy waits for 3 seconds and then it stops working. The only thing I can think of is that the wait gets called every frame so that after the first wait you can't 'see' it waiting anymore. Anyway, here's the code:

 void FixedUpdate(){
 
 
         StartCoroutine (directionGetter ());
 
     
     }
 
     IEnumerator directionGetter(){
         while (true) {
                         yield return new WaitForSeconds (3f);
                         directionChange = Random.Range (1, 5);
                         if (directionChange == 1) {
 
                                 myTransform.Translate (Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
                                 
                         }
 
                         if (directionChange == 2) {
             
                                 myTransform.Translate (-Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
                                 
                         }
     
                         if (directionChange == 3) {
             
                                 myTransform.Translate (Vector3.right * enemySpeed * enemyHealth * Time.deltaTime);
                                 
                         }
     
                         if (directionChange == 4) {
             
                                 myTransform.Translate (-Vector3.right * enemySpeed * enemyHealth * Time.deltaTime);
                                 
                         }

Thanks in advance for any help ^_^

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

2 Replies

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

Answer by highpockets · Mar 10, 2014 at 02:16 AM

Create a bool system for checking if the coroutine is running. In fixed update put this:

 bool inRoutine = false;
 
 void FixedUpdate()
 {
 
 if( !inRoutine )
 {

 inRoutine = true
 StartCoroutine( DirectionGetter());
 }
 }
 
 IEnumerator DirectionGetter()
 {
 
 while( inRoutine )
 {
 
 yield return new WaitForSeconds (3);
 directionChange = Random.Range( 1, 5 );
 
 if( directionChange == 1 )
 {
 
 myTransform.Translate(Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
 }
 
 //your other code...
Comment
Add comment · Show 3 · 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 highpockets · Mar 10, 2014 at 02:20 AM 0
Share

There is another problem though, how long do you want the enemy to walk for? Or what distance?? Because right now, the enemy will walk for one frame and then wait. It will be like nothing happened.. You could have another while statement that remains true until the enemy moves to the location you choose or walks for a certain amount of time. But the code above will ensure only one Coroutine runs at once

avatar image highpockets · Mar 10, 2014 at 02:43 AM 0
Share

If you want to make the enemy walk for a certain amount of time. You can do this:

 if( directionChange == 1 )
 {
 
 var walkTime = 3 + Time.time;
 
 while( walkTime > Time.time )
 {
 myTransform.Translate(Vector3.up * enemySpeed * enemyHealth * Time.deltaTime);
 yield return null;
 }
 }
  
 
avatar image Coned_Stoding_games · Mar 10, 2014 at 03:03 AM 0
Share

thank you very much that has totally sorted my issue :) you're right that their movement being frame dependant wasn't great, it was workable, but having the Time.time/while loop really brought it to life. Thanks again for all your help!

avatar image
0

Answer by SirCrazyNugget · Mar 10, 2014 at 02:19 AM

There is nothing to stop it working in what you've shown

 IEnumerator directionGetter(){
    while(true){
       yield return new WaitForSeconds(3f);
       //do
 
    }
 }

This will keep repeating every three seconds as you'd expect, just make sure you don't have a break or another return somewhere down the bottom of what you've pasted.

Also take a look at the switch statement instead of using multiple ifs, rules of thumb if you're using more than three ifs use a switch, if you're using three or less use "else if". Currently your code is checking every directionChange even though it's known to only ever be one.

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 Coned_Stoding_games · Mar 10, 2014 at 03:07 AM 0
Share

Hey, thanks I'll definitely look into using switch statements ins$$anonymous$$d, and yes else ifs would have been better, I realise this, however I didn't realise that all the statements beings ifs would make the game more cpu intensive thanks for that tidbit. As for saying the code should work - it didnt, and there weren't any breaks etc after what I posted - only the last closing brace. It wasn't working because the enemy would only pause for three seconds at the beginning of the coroutine and then it wouldn't wait again. But now with highpockets' code it does.

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

22 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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Adding a bar that reset for each level 4 Answers

how can i auto target Gameobject on startup 1 Answer

Run Coroutine once, but finish Lerping 2 Answers


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