- Home /
StartCoroutine for each object in a foreach() Loop
I am having some issues getting my head around the Coroutine concept in C#
Question
I have a list of objects that I want to manipulate via a script but I want that action to be preformed a frame latter for each consecutive object so as to reduce the load on the CPU.
My sudo code is as follows:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
void MainAction(GameObject[] TargetList){
int Loop = 0;
foreach (GameObject Target in TargetList){
StartCoroutine(Action(Loop,Target));
Loop++;
}
}
IEnumerator Action(int Loop,GameObject Target){
yield return new WaitForSeconds(Loop/2f);
Target.transform.localScale = new Vector3(0,0,0);
}
void Update(){
GameObject[] TargetList = GameObject.FindGameObjectsWithTag("Target");
MainAction(TargetList);
}
}
Any help would be really appreciated!
From your pseudo code it seems that each frame you will run the main action, which (still in each frame) would loop through all the objects and execute your coroutines. Is this what you meant to do? I mean this could be fine, if something clears your target list immediately after it was sent to the main action method.
Thanks for the help, I am gona have to look at my main code a bit more as this sudo code seems to work fine.
Answer by MCHammond · Dec 17, 2012 at 04:54 PM
Hmm...
I just used my Sudo code in a fresh project and it seems to work :/ I guess that there is an issue with my main code other than my understanding of Coroutine.
I have updated My original Sudo Code with the Code I used in my blank Project that works so that others searching for an example of Coroutine code can see it.
I have marked this as correct because my question answers itself and the updated Sudo code does what I wanted it to do.
Your answer
![](https://koobas.hobune.stream/wayback/20220613085547im_/https://answers.unity.com/themes/thub/images/avi.jpg)