Wait for seconds inside for loop between function execution

I am trying to add a 2 sec wait after the destroy:

  • foreach (GameObject g in gemList1)
  • {
  • Destroy(g);
  • //want to add a time delay of 2 secs here
    • }

Invoke cant work because I have a parameter. Also IEnumerator seems to be prefixed before the function. Thanks for your ideas.

IEnumerator seems to be prefixed before the function? :slight_smile: Like you read this elsewhere?

You’re looking for a Coroutine : calls an IEnumerator function and can yield for seconds, amongst other things.

IEnumerator GemDestroy() {
   WaitForSeconds wfs = new WaitForSeconds(2);
   for(int i = 0; i < gemList.Count; ++i) // this presumes gemList is type 'List', must be '.Length' if it's an array.
      Destroy(gemList[i]);
      yield return wfs;
   }
}

And call it like this: StartCoroutine(GemDestroy());

Check this out for more depth, if you’re interested:

3 Likes