- Home /
Delete Instantiated object?
Hello im making a game were if i use a card a human summons on an island and i also have a card that removes humans but how do i only remove one clone??
this is my instanciate script:
if(manager.population < manager.maxPopulation)
{
manager.population++;
print("card 1 used");
Instantiate(human, humanSpawner);
}
Here is where i want to remove 1 human:
if (manager.population > 0)
{
manager.population--;
print("Card 2 used");
}
Answer by Hellium · Dec 16, 2018 at 10:47 AM
You have to keep a reference to the instantiated object somewhere.
You can use a dynamic set you containing your instantiated object (such as a List
). Depending on how the objects must be destroyed, you may be interested by the Stack
(last one added is the first one deleted) or the Queue
(first one added is the first one deleted).
private Queue<GameObject> humans = new Queue<GameObject>();
// ...
if(manager.population < manager.maxPopulation)
{
manager.population++;
print("card 1 used");
humans.Enqueue( Instantiate(human, humanSpawner) ) ;
}
// ...
if (manager.population > 0)
{
manager.population--;
print("Card 2 used");
Destroy( humans.Dequeue() ) ;
}
I get this: InvalidOperationException: Operation is not valid due to the current state of the object
On the Destroy( humans.Dequeue() ) ;
You may need to check whether the queue contains element before:
if (manager.population > 0)
{
manager.population--;
print("Card 2 used");
if( humans.Count > 0 )
Destroy( humans.Dequeue() ) ;
}
The error dissaperared but it wont destroy the objects