title: How to wait for a method to finish before moving on the next line of code in Unity?
body: <p>I want to make an Visualization of quick sort using game objects. The problem is, when I put the method inside the quicksort method it doesn't wait for the animation to finish. The code executes all the lines at the same time. </p>
  
  <p>I want to make the method execute first then proceed to the next line. I already tried the IEnumerator function but the sequence is rearranged if I use yield <code>return StartCoroutine ( myfunction() )</code>; quick sort is in a recursive sequence. At first the animation works but when the recursion happens, the yield return is not working any more. </p>
  
  <p>Here is my code in C#:</p>
  
  <pre><code>IEnumerator swapElement(int e1, int e2)
  {
      swap = true;&lt;br&gt;
      go1 = GameObject.Find ("Element" + e1);&lt;br&gt;
      go2 = GameObject.Find ("Element" + e2);
  
      go1xpos = go1.GetComponent&lt;Transform&gt; ().transform.position.x;
      go2xpos = go2.GetComponent&lt;Transform&gt; ().transform.position.x;
      go1ypos = go1.GetComponent&lt;Transform&gt; ().transform.position.y;
  
      x1ps = go1xpos;
      x2ps = go2xpos;
  
  
      go1.GetComponent&lt;Transform&gt; ().transform.position = new Vector3 (x2ps, go1ypos);
      go2.GetComponent&lt;Transform&gt; ().transform.position = new Vector3 (x1ps, go1ypos);
      yield return new WaitForSeconds (5);
  
      Debug.Log ("INSIDE SWAP : LEFT : " + e1 + " RIGHT : " + e2);
  
  }
  </code></pre>
  
  <p><br>
  <br></p>
  
  <p>Sort Method:</p>
  
  <pre><code>int l, r;
  
  int partition(int[] numbers, int left, int right)
  {
  
      int pivot = numbers [ (left + right) / 2];
  
      while (true) 
      {
          while (numbers [left] &lt; pivot) left++;
          while (numbers [right] &gt; pivot) right--;
  
          if (left &lt; right) 
          {
              int temp = numbers [right];
              numbers [right] = numbers [left];
              numbers [left] = temp;
  
              //Debug.Log ("LEFT : " + left + " RIGHT : " + right);
  
              swapElement (left, right);
  
          }
          else 
          {
              return right;
          }
  
      }
  
  }
  
  
  void quickSort(int[] arr, int left, int right)
  {
  
      if (left &lt; right) 
      {
          int piv = partition (arr, left, right);
  
          if (piv &gt; 1) quickSort (arr, left, piv - 1);
          if (piv + 1 &lt; right) quickSort (arr, piv + 1, right);
      }
  
  }
  </code></pre>
  
  <p>I already tried <code>startcoroutine( swap (left, right) )</code>, but no luck.<br></p>
  
  <p>I can put the animation inside the swap method but even then it is still the same: It executes at the same time.</p>
  
  <p>additional information : <br> if I use IEnumerator, the recursion is not working. but if in void, It is working however, the void is not waiting for the animation method to finish. it executes at the same time.</p>