Destroying assets is not permitted to avoid data loss?
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]);
Answer by Bunny83 · Apr 29, 2018 at 04:20 PM
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.
RE: only that 1st sentence: in the broader game design world, Spawn is a synonym for Instantiate. Those code comments seem fine to me.
But otherwise, yes, the OP should take another look at the manual.
Yes, spawn is an abstract term and loosly means "bring something into existence". Though depending on the context it can mean something different. Like in a networking environment "spawning" could only mean "activating". It's still the same concept of bringing it into existence but does not necessarily mean Instantiating / creating / cloning. The same holds true when you use object pools where you don't create and destroy objects but reuse them and only create / clone one if the pool is empty. To be a synonym it has to work in both directions. If you say Instantiate is equal to spawning it means spawning is equal to Instantiate which is not always the case. So you could say Instantiate is a more concrete example of spawning
To be more clear, in older game engines Spawn(a) is the command that Unity renamed Instantiate(a).