Search Unity

Wait for seconds inside for loop between function execution

Discussion in 'Scripting' started by starazure, May 29, 2017.

  1. starazure

    starazure

    Joined:
    May 28, 2017
    Posts:
    31
    I am trying to add a 2 sec wait after the destroy:

    1. foreach (GameObject g in gemList1)
    2. {
    3. Destroy(g);
    4. //want to add a time delay of 2 secs here
    5. }
    Invoke cant work because I have a parameter. Also IEnumerator seems to be prefixed before the function. Thanks for your ideas.
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    IEnumerator seems to be prefixed before the function? :) Like you read this elsewhere?

    You're looking for a Coroutine : calls an IEnumerator function and can yield for seconds, amongst other things.
    Code (csharp):
    1.  
    2. IEnumerator GemDestroy() {
    3.    WaitForSeconds wfs = new WaitForSeconds(2);
    4.    for(int i = 0; i < gemList.Count; ++i) // this presumes gemList is type 'List', must be '.Length' if it's an array.
    5.       Destroy(gemList[i]);
    6.       yield return wfs;
    7.    }
    8. }
    9.  
    And call it like this:
    Code (csharp):
    1.  StartCoroutine(GemDestroy());

    Check this out for more depth, if you're interested:
    https://unity3d.com/learn/tutorials/topics/scripting/coroutines?playlist=17117
     
    pedroarruda4991, Lethn and Ryiah like this.