• 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
Question by hballamco · Dec 03, 2019 at 02:12 AM · vector3coroutineyieldtranslatenull

Object keeps moving up even when StopCoroutine is called

Hello guys, I'm trying to move an object in the "up" direction whenever the player enters a collider using OnTriggerStay. I used the code below w$$anonymous$$ch includes a Coroutine.

 if (other.gameObject.tag == "Puzzle2") // fence2 closes on puzzle2 smoothly
         {
             StartCoroutine("Fence2Up");
         }
     }
 
     IEnumerator Fence2Up()
     {
         fence2.transform.Translate(Vector3.up * Time.deltaTime * 3);
         new WaitForSeconds(6f);
         print("It should stop!");
         StopCoroutine("Fence2Up");
         yield return null;
     }

 

The if statement is in the "OnTriggerStay " function. Basically, the object correctly moving upward whenever I enter the collider. Yet, It doesn't stop after 6 seconds w$$anonymous$$ch I specified in the IEnumerator function where I mentioned StopCoroutine. Also, the print function works properly after 6 seconds.

Comment

People who like this

0 Show 0
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
Best Answer

Answer by Anis1808 · Dec 03, 2019 at 02:25 AM

It seems like you are still staying in the trigger so you should only call the coroutine once. So just create a boolean named startedCoroutine and it should work.

 if (other.gameObject.tag == "Puzzle2" && !startedCoroutine) 
          {
              StartCoroutine("Fence2Up");
              startedCoroutine = true;
          }
      }

EDIT

Another problem with the code is that new WaitForSeconds(6f); does not do much, you have to call yeild return new WaitForSeconds(6); for it to actually wait 6 seconds.

What I suggest is that you don't use a coroutine at all and use Update instead, like t$$anonymous$$s

 float timeLeft = 6f;
 bool runCode;
 
 void Update(){
           if(runCode){
                    timeLeft -= Time.deltaTime;
                    if(timeLeft>0){
                              fence2.transform.Translate(Vector3.up * Time.deltaTime * 3);
                    }
           }
 }
 
 void OnTriggerStay(Collider other){
           if (other.gameObject.tag == "Puzzle2" && !runCode) 
           {
               runCode= true;
           }
 }
 


Comment
hballamco

People who like this

1 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 hballamco · Dec 03, 2019 at 02:32 AM 0
Share

Thanks for the reply, I tried what you said but unfortunately I didn't get the result needed. What happens is that the object didn't move at all. Plus, the print function showed up immediately ignoring the 6 seconds condition that I specified.

avatar image Anis1808 · Dec 03, 2019 at 03:15 AM 0
Share

Updated my code, it should work better now.

avatar image hballamco · Dec 04, 2019 at 03:45 AM 0
Share

@Anis1808 Indeed, I don't need to use Coroutine function. I got what I want. Thanks to you and I appreciate your effort and time.

avatar image

Answer by Ermiq · Dec 03, 2019 at 08:58 AM

Your usage of the coroutine is all wrong.


Coroutine should contain a conditional loop (`w$$anonymous$$le`) or conditional statement (`if`), and the code that should be executed continuously must be placed inside t$$anonymous$$s loop/statement scope.
The scope then should end up with one of the yield return instructions determining when the next iteration should be executed again. Note that the yield return should be inside the loop/statement scope.


Once the condition return false, the coroutine is over, and the execution order will go to outside of the condition scope.


So, if you want to continuously move the transform up for 6 seconds (I t$$anonymous$$nk that's what you're trying to do), you should call the coroutine t$$anonymous$$s way:

 IEnumerator Fence2Up()
 {
     // the counter will be substructed with Time.deltaTime after every coroutine iteration
     // and we'll execute next coroutine step every frame using yield return null
     float counter = 6f;
     // set up the condition that will determine if the coroutine should be executed again or not
     w$$anonymous$$le (counter > 0)
     {
         print("Coroutine is running, counter=" + counter);
         fence2.transform.Translate(Vector3.up * Time.deltaTime * 3);
         counter -= Time.deltaTime;
         print("Gonna wait for next frame to continue");
         yield return null;
         // here the coroutine will be paused untill the next frame
         // and in the next frame it will execute the code inside the w$$anonymous$$le scope again if the counter will still be more than 0
         // if you use WaitForSeconds here instead of yield return null,
         // the coroutine will be paused for 6 seconds and it will move the transform and substruct counter only every 6 secods
     }
     // if the counter is 0, then the coroutine will stop itself
      print("The coroutine has stopped because the counter is 0 or less. Counter=" + counter);
      // no need to stop the coroutine, it already has stopped itself
  }

And don't use OnTriggerStay() since you use a coroutine here. Because it just doesn't make sense. Coroutines are designed to be called just once and once you've called the coroutine, it will call itself automatically if the condition inside the coroutine is true. That's what coroutines are made for.


So, if you want to move the fence for 6 seconds whenever player gets into the trigger area, use OnTriggerEnter() w$$anonymous$$ch is called just once, and you won't have to stop and restart the coroutine manually. You call the coroutine once and it recalls itself automatically w$$anonymous$$le the condition is true and then stops itself.

Comment
hballamco
Legend_Bacon

People who like this

2 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 hballamco · Dec 04, 2019 at 03:47 AM 0
Share

I'm new to Unity and your comment added so much to my knowledge. Thanks for replying and I appreciate your effort.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

150 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 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 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 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 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 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

Code working on wrong axis. 1 Answer

yield troubles. function needs to finish before continuing 1 Answer

Translate and Yield giving inaccurate results? 2 Answers

WaitForFixedUpdate coroutine happens after the internal physics update? 1 Answer

WWW isDone when lost internet connection, it return true and not wait for internet connection (Andriod) 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