Hello, I’m looking to use the following code to destroy a list of GameObjects, but I also instantiate another list of GameObjects in the same frame with the possibility of having the same tags. I know I could use DestroyImmediate, but the docs recommend against it ESPECIALLY in for loops. I can’t use a yield WaitUntilEndOfFrame because it is a static function. Any ideas?
var gos = GameObject.FindGameObjectsWithTag("Pads");
for (var j = 0; j < gos.Length ; j++)
Destroy(gos[j]);
The problem here is you using FindGameObjectsWithTag.
This is when your newly instantiated objects will most probably have the same tag, and end up being added to the gos variable and being deleted.
The best approach is to use Lists (or arrays since you’re using Javascript), loop through the old one delete everything and instante new ones in a new array.
That way, you don’t really care about naming.
But if you want to keep that approach, the best way is to use coroutines,
I wrote you a code in C# (you can use it, or just change it to Javascript), when i start deleting, and only when the deletion call finishes, i start instantiating.
GameObject gos[];
IEnumerator Start(){
gos = GameObject.FindGameObjectsWithTag("Pads");
//Start and wait for DestroyMyGameObjects to finish
yield return StartCoroutine("DestroyMyGameObjects");
//This will only be called when the first Coroutine is finished
InstantiateGameObjects();
}
//The coroutine
IEnumerator DestroyMyGameObjects(){
foreach(GameObject g in gos){
Destroy(g);
}
yield return null;
}
//The function to call when the coroutine is finished
void InstantiateGameObjects(){
//Instantiate Code
}