Hey guys,
I Have a Issue with destroying my Gameobject. I can’t see the problem here because I’am using the Destroy() function like this every time.
I hope you can help me out :).
Source:
// sets the point where the obstacle has to spawn
Transform spawnpoint = spawnPoints[spawnIndex];
// sets the rotation of the spawnpoint
spawnPoints[spawnIndex].rotation= Quaternion.Euler(new Vector3(0f,0f,Random.Range(0f, 90f)));
// Spawns the actual Obstacle
Instantiate(obstacles[obstacleIndex], spawnpoint.position, spawnpoint.rotation);
yield return new WaitForSeconds(5f);
// Destroy the same Obstacle after 5s
Destroy(obstacles[obstacleIndex]);
Instantiate does not “spawn” the given object but it creates a duplicate of it in the scene. That newly created duplicate is returned by the Instantiate method. The object stored in the obstacles array is still the prefab in your project. You do not try to destroy the instance you’ve created but you try to destroy the source object, specifically the prefab of your project.
You have to do:
var instance = Instantiate(obstacles[obstacleIndex], spawnpoint.position, spawnpoint.rotation);
yield return new WaitForSeconds(5f);
Destroy(instance);
Though this could even be simplified and handled without a coroutine all together since the Destroy method can take a second “delay” parameter. So you could just do
Destroy(Instantiate(obstacles[obstacleIndex], spawnpoint.position, spawnpoint.rotation), 5);
and it will create that obstacle and will automatically destroy it after 5 seconds. Though if you plan to use an object pool in the future my first example would be the better one as it can be changed more easily to use an object pool instead of Instantiate and Destroy.