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:

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);
}

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 :slight_smile: )

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*.Destroy();*

}
objects.clear();
}
void SpawnAllObstacles() {
for (int i = 0; i < obstacleCount; i++) {
SpawnObject()
}
}
void SpawnObject() {
Vector3 pos = Vector3.Zero;
objects.add(Instantiate({Parameters here}));
}
}