Search Unity

Coroutine help!

Discussion in 'Scripting' started by adentutton, May 12, 2016.

  1. adentutton

    adentutton

    Joined:
    Mar 24, 2013
    Posts:
    34
    Hey guys

    I am working on a sports sim of Volleyball where the ball moves to various areas of the court and the movement of the players is driven by where the ball goes, so I have to wait until the ball gets to its destination before starting its next movement. I have gotten as far as the code below

    Code (CSharp):
    1. IEnumerator ServeA () {
    2.        
    3.         while (Vector2.Distance(ball.transform.position, serve_left[4]) > 0.01f) {
    4.  
    5.             ball.transform.position = Vector2.MoveTowards (ball.transform.position, serve_left [4], speed);
    6.  
    7.         }
    8.  
    9.         yield return null;
    10.  
    11.         print("Reached the target.");
    12.  
    13.         yield return new WaitForSeconds(3);
    14.  
    15.         print("MyCoroutine is now finished.");
    16.  
    17.     }
    18.  
    19.     void Start () {
    20.  
    21.         StartCoroutine (ServeA ());
    22.  
    23.     }
    As a beginner I may be miles off! My while loop is trying to find the distance between the balls current position and destination (Vector2 in an array of coordinates) but right now ball goes immediately to its destination with no movement

    Look forward to your feedback!
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Remember that coroutines evaluate EVERYTHING in one frame until the yield is reached. If you want each iteration of the while loop to execute in each frame, try putting the yield inside of the while loop after line 5. It should execute the position update, then yield. Next frame, it will pick up at the end of the while loop, and check the while condition again. If it's true, it will update position again then yield again, etc.