They appear and disappear, as if by magic!
You are playing a multiplayer game, you are winning and you have a nice kill streak. Suddenly, a player pops out of existence behind you, and ends that streak. You curse at the badly positioned respawn positions and the manager handling it.
As all games, they all count with a functionality to spawn or despawn certain elements in levels. Unity has two built-in methods that will let you do this in any script.
With a given GameObject or Component as a reference, Instantiate will clone that and conserve its properties and values.
This method counts with an amount of overloads (variations of the same method), but overall, two of them are the complete versions of the rest.
- T Instantiate(T original, Transform parent, bool instantiateInWorldSpace)
- T Instantiate(T original, Vector3 position, Quaternion rotation, Transform parent);
- T original is a reference to the object to clone.
- Transform parent will assign that clone as a child of a given Transform
- bool instantiateInWorldSpace let us decide if we want to spawn that clone in the world space or the parent space (a child’s position is relative to its parent).
- Vector3 position is an specific world position where it will spawn that clone.
- Quaternion rotation is the rotation that will modify the original clone’s rotation.
As simple as that, you can create clones of any object you want. Projectiles, enemies, power-ups… you name it!
When in doubt, always check the Unity API: Instantiate.
As the method’s name says, it destroys a selected Object permanently.
- Destroy(Object obj)
- Destroy(Object obj, float t)
- Object obj is the object to destroy.
- float t is a time given to delay the destruction of that object. If you want an immediate destruction, use the first method.
Imagine you are making an autoscroller game, and you leave behind other GameObjects that you’ll never see again. Still, even if you leave, those objects remain in the scene forever. It would make sense to destroy or despawn them to improve our game optimization.
Another example could be disposing of enemy bodies after some time. We don’t want a million bodies lying on the ground and explode the player’s computer. We use Destroy to keep our scene clean, and our performance high.
For more information, read the Unity API: Destroy
You are ready to start spawning and despawning whatever you want! Nice and easy.
In a future article, I will talk about some issues about abusing these methods, what could that mean to the performance of our game, and one way to solve those problems. But, in the meantime, enjoy yourself using these methods, and remember to follow me for more articles!
// EDIT: The next articles will be related to the 2D Space Shooter game I’m making, to keep my content consistent.