- Home /
DestroyImmediate alternative?
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]);
Actually, it's not an issue if they have the same name but rather the same tag. I have a counter in the same frame that will count all objects with the tag and output the number, so if they don't delete first it counts all new GameObjects and the ones that should be deleted.
Answer by _joe_ · Mar 29, 2015 at 04:16 PM
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
}
That's exactly what I needed! I guess it was just multiple scripts running at once in the same frame, I just needed to do "yield StartCoroutine" to do them sequentially. It's odd that I'm using $$anonymous$$onoDevelop and it doesn't even give me the option to do yield StartCoroutine, I just tried it and it worked! Cheers!
Your answer
Follow this Question
Related Questions
Trouble with Object Pooled Enemy Waves 0 Answers
blasting the current object, if it touches anything 0 Answers
Does UnityEngine.Object.DestroyImmediate() invoke PrefabUtility.PrefabInstanceUpdated? 0 Answers
destroyImmediate on children not working correctly? 6 Answers
Error destroying prefab 1 Answer