Multiple calls to Destroy for same instance

I have a scenario where a gun is rapid firing some projectiles that should self-destruct after 3 seconds, or when they collide with another object. Is it a problem to just call Destroy(foo, 3) right off the bat, but then call Destroy(foo) from the collision event? I would expect the second Destroy just resets the clock on the delayed Destroy, but I figured it can’t hurt to ask…

I’m pretty sure Unity handles that gracefully. The only edge case I can imagine is if there really are pending destroy events, then two could conceivably take place on the same frame, one after the other, but I think Unity is fine with that, as long as you don’t keep a reference and try to destroy it the NEXT frame.

In fact, let’s TEST it! You can run this code on your favorite version of Unity and see for yourself. Unity 5.2.2f1 does not complain about this code at all:

using UnityEngine;
using System.Collections;

public class DestroyingThings : MonoBehaviour
{
    IEnumerator Start ()
    {
        // frame 0: // make a cube
        GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);

        yield return null;

        // frame 1: destroy it once
        Destroy (cube);
        // destroy it again!
        Destroy (cube);        // unity seems happy

        yield return null;

        // frame 2: destroy the destroyed cube
        Destroy (cube);        // unity is even happy the next frame
    }
}

Rest in peace poor cube. You will not be forgotten.

3 Likes