- Home /
Destroy Objects after a set time
I know this question has been asked before, but I am still confused and have tried multiple methods (like Object.Destroy(obstacle, 2.0f and such) and all has failed. I am coding a game that drops obstacles (20) onto a plane, and Every 5 seconds I want the game to destroy the objects and make new ones fall (So it doesn't clog the game and new objects can form) My code is:
Answer by RendrWyre · Jan 09, 2020 at 08:34 PM
You could attach a script to the GameObject prefab that you spawn that is responsible for destroying itself after 5 seconds. There's probably a more elegant way to do it within a single script with lists or something but maybe you just want something quick and simple.
Start()
{
StartCoroutine(SelfDestruct());
}
IEnumerator SelfDestruct()
{
yield return new WaitForSeconds(5f);
Destroy(gameObject);
}
Answer by Owlfrog · Jan 09, 2020 at 08:12 PM
When you're instantiating the obstacle, it returns a reference to the game object that is created. So one approach you might be able to take is adding a list to the class; and then when the time is up, loop through and destroy the objects in the list and clear the list.
Something like this (note this is not compilable code, since I couldn't copy & paste your screenshot code :) )
class MyObstacleSpawner {
List<GameObject> objects = new List<GameObject>();
float timeToRecreateObjects = 5f;
void Update () {
if (timeToRecreateObjects <= 0f) {
SpawnAllObstacles();
timeToRecreateObjects = 5f;
} else {
timeToRecreateObjects -= Time.deltaTime;
}
}
void DeleteObjects() {
for(int i = 0; i < objects.size; i++) {
objects[i].Destroy();
}
objects.clear();
}
void SpawnAllObstacles() {
for (int i = 0; i < obstacleCount; i++) {
SpawnObject()
}
}
void SpawnObject() {
Vector3 pos = Vector3.Zero;
objects.add(Instantiate({Parameters here}));
}
}
Ins$$anonymous$$d of just destroying the objects, in my opinion, it would be much better to add them to an object pool. That way, if you have any objects in the object pool you can use them ins$$anonymous$$d of creating new ones to improve performance.
True. OP does appear to already know the maximum number of gameobjects (20) and it would remove the need to allocate and deallocate memory on instantiation and destruction.