Suppose for example if I’m creating 5 gameobject
I want to destroy the objects from the last i.e. 5th object,4th object…1st object in this order I want to get deleted is this possible.
Suppose for example if I’m creating 5 gameobject
I want to destroy the objects from the last i.e. 5th object,4th object…1st object in this order I want to get deleted is this possible.
You need to keep track of the objects you are creating. Thankfully, there exists a classic data structure for doing exactly this!
First off, import System.Collections.Generic (which you should always do, because it has simply the best classes)
// at the top!
using System.Collections.Generic;
Now make a Stack of GameObjects (like this):
Stack<GameObject> goStack = new Stack<GameObject>();
Now, whenever you create a new GameObject, add it to the stack like this:
goStack.Push(newObject);
Then, when you want to get the most recent object (to delete it) use this:
GameObject destroyMe = goStack.Pop();
Destroy(destroyMe);
This will return your most recent object, and remove it from the stack. The next time you call ‘Pop’ it will return the next most recent, and so on, until you get to the end (having destroyed every object).