Strange behavior of GameObject.Destroy
Hello, I faced some strange things in behavior of GameObject.Destroy. I have an instance of MyClass which contains an array of GameObjects and method MyDestroy (i'll explane using of the delegate below):
for (int i = 0; i < Objects.Count; i++)
{
if (Objects[i] != null)
{
var j = i;
new Action(() => UnityEngine.Object.Destroy(Objects[j])).Invoke();
}
}
So it perfectly works and objects disappear from screen pretty quick but if I put this Action in queue and then dequeue and invoke it in other GameObjects nothing happens.
for (int i = 0; i < Objects.Count; i++)
{
if (Objects[i] != null)
{
var j = i;
DestroyManagerInstance.Enqueue(() => UnityEngine.Object.Destroy(Objects[j]));
}
}
//---------------------------------Other-class-code--------------------------
public class DestroyManager : MonoBehaviour
{
private Queue<Action> Queue;
public void Enqueue(Action a)
{
Queue.Enqueue(a);
}
// Use this for initialization
void Start()
{
Queue = new Queue<Action>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Queue.Any())
{
Queue.Dequeue().Invoke();
DebugLog("DestroyQueueEvent");
}
}
}
However i see a lot of "DestroyQueueEvent" in unity Console and there are no errors in both cases. In my opinion when i write something like this
DestroyManagerInstance.Enqueue(() => UnityEngine.Object.Destroy(Objects[j]));
a tricky .Net creates an instance of anonymous class which contains reference to my Objects[j] and it's equivalent to closure in fuctional programming languages so it doesn't matter where i invoke the delegate. But i see the different behavior. Can you point me where problem can be? Also i'll be happy if you recommend me how to avoid lags when i destroy 64*64*4 GameObjects without batching it with delegates (for creating this method works correctly).
gameObject.Destroy();
Doesn't immediately destroy the gameobject. It will stay there until the next frame. You could try gameObject.DestroyImmediate();
but it's highly not recommended.
I know about behavior of .Destroy, but when i say "nothing happens" i mean "Hey, it's been five $$anonymous$$utes, but all the objects are still here".
Oh. Lol. Well, the Unity Wiki does say: "Note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general program$$anonymous$$g practice, not just in Unity)."
Your answer
![](https://koobas.hobune.stream/wayback/20220612164454im_/https://answers.unity.com/themes/thub/images/avi.jpg)