Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Regarding Yielding in a coroutine

Discussion in 'Scripting' started by BFDesign, Dec 4, 2012.

  1. BFDesign

    BFDesign

    Joined:
    Mar 16, 2011
    Posts:
    214
    Good morning, all.

    I'm having trouble wrapping my head around this one. I have a little snippet wherein I will play an animation, have it wait for a second or two after the animation is complete, and then repeat the process. I'd figured it would have to work like this but I guess I'd figured wrong.
    Here is the code exactly as it written. I would appreciate any help at all on this. Thank you very much in advance.

    Code (csharp):
    1. var x : float;
    2.  
    3.  
    4. function Update(){
    5.  
    6.      Animate();
    7.      
    8.      
    9.      }
    10.  
    11.  
    12. function Animate() {
    13.    
    14.         animation.Play("Take 001");
    15.        
    16.         yield WaitForSeconds(x);
    17. }
     
  2. Landern

    Landern

    Joined:
    Dec 21, 2008
    Posts:
    354
    So yielding... you can think of it like placing a book mark to come back to for a later time(execution), when you call yield, everything happens after the yield(including after the Animate() function call in update) when yielding. In your case you would be playing an animation every single frame, i'm sure the animation doesn't even complete.

    Code (csharp):
    1.  
    2. var x : float;
    3.  
    4. function Update(){
    5.      Animate();
    6.      }
    7.  
    8. function Animate() {
    9.         // If the named animation is not playing, play it.
    10.         if (animation.IsPlaying("Take 001") == false) {
    11.            animation.Play("Take 001");
    12.         };  
    13.      
    14.         //yield WaitForSeconds(x);
    15. }
     
  3. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,697
    Update is called every 33 ms or something ridiculous. The way you have constructed your code is to call Animate() every 33 ms.

    What you need to do is place a breaker.

    Without being too precise....
    Code (csharp):
    1.  
    2. function Update()
    3. {
    4. if(animating == false)
    5. Animate();
    6. }
    7. function Animate()
    8. {
    9. animating = true;
    10. ///do stuff
    11.  
    12. /// yield
    13. /// after animation complete....
    14. animating = false;
    15. }
    this will play an endless loop of your animation.
     
  4. BFDesign

    BFDesign

    Joined:
    Mar 16, 2011
    Posts:
    214
    Thank you to both of you for your responses! Makes more sense than the documentation I found. I will get on implementing this immediately.
    Again, thank you for your time and consideration.