single scene restart (efficiency question)

Hey, I have almost finished my game, now, I’ve stumbled upon a crossroad, In my game I instantiate 2 object randomly between 2 position, in the middle of the game I die but the instantiated object still there what leaves me wondering what’s the best method of making them disappear, I mean, finding all the instantiated objects and destroying them seems a little too much, I don’t want the phone memory to overwork, does anyone have a different idea on how to do it the best way to do it?

I cant really think of any other way, when you instantiate them, save everything you plan to delete later into one array, when you want to delete everything, clear the array?

Or, give them a “lifetime”, or a dependency variable, make a global “GameOver” boolean, and have in the update check if that variable is true, then destroy itself?

Or try Application.LoadLevel(Application.LoadedLevel) and just reload the level completely, which would technically delete those objects

As far as efficiency goes, I cant think of any other way you could delete everything at once without making the computer do some kind of work, the dependency variable with the global “GameOver” boolean might be the least working system, because they delete themselves instead of the game trying to delete x number of objects at once

The easiest thing would be to create a callback in the player, and allow everything to react to that:

public class Player : MonoBehaviour {

    public Action OnDead;

    ...

    
    private void Die() {
        //Do all the respawn stuff and whatever

        if(OnDead != null) { // if any callbacks have been registered
            OnDead();
            OnDead = null;//If you want to clear all callbacks
        }
    }
}

And when you create the two objects:

GameObject someObject = Instantiate(...

player.OnDead += () => Destroy(someObject);

Action is a built-in C# thing (available in UnityScript too) that allows you to add function calls to a list. When you call it, you call all those functions at once. You can read about it here. The "() => " thing is an lambda expression, which you can read about here.

If creating and destroying these objects are too resource intensive (doubtfull if it’s only two), you could hide them instead of destroying them, and then just move them back to where you would have created them and unhide them again later. That’s a lightweight form of what’s usually refered to as an “object pool”, where you reuse objects instead of creating new ones.