Instantiating OnDestroy()

I’m instantiating objects in OnDestroy and getting the following error whenever I exit ‘Play Mode’:

Some objects were not cleaned up when closing the scene. (did you spawn new GameObjects from OnDestroy?)

Why, yes. Yes I did. I saw a few threads saying that you should just not instantiate objects from OnDestroy, but I don’t really understand why. It would be convenient to create a new game object upon another’s removal. Specifically what I’m using it for is a Prefab of various environmental objects like bushes or trees that become randomized on Awake() by deleting destroying itself and instantiating a new game object of similar category (with slightly randomized size and tint) in its transform position.

Is there a better way of accomplishing this? Here’s the code I wrote for the Randomizer Prefabs. At the moment, the Prefabs get destroyed on Awake() in a separate one-line script which I’ll probably move into this script and then this ‘newObj’ gets created in its place:

public class ObjRandomizer : MonoBehaviour
{
    public GameObject[] objArray;
    public float tintMargin;
    public Vector3 sizeMargin;

    void OnDestroy()
    {
        Vector3 location = transform.position;
        GameObject obj = objArray[Random.Range(0, objArray.Length)];
        var newObj = Instantiate(obj);
        int flip = Random.Range(0, 2);
        newObj.transform.position = location;
        newObj.transform.eulerAngles = new Vector3(global.cameraAngle * (1 - 2 * flip), flip * 180, 0);
        newObj.GetComponentInChildren<SpriteRenderer>().color = new Color(1.0f - Random.value * tintMargin, 1.0f - Random.value * tintMargin, 1.0f - Random.value * tintMargin, 1);
        newObj.transform.localScale += new Vector3 (sizeMargin.x * (1 - 2 * Random.value), sizeMargin.y * (1 - 2 * Random.value), sizeMargin.z * (1 - 2 * Random.value));
    }
}

It’s generally not a “bad thing” but keep in mind that GameObjects can be destroyed in a variety of ways.

  • Via code
  • Unloading a scene
  • Exiting play mode in the Editor
    That last one is why you’re seeing that message.
1 Like