Instantiation and Destruction of GameObjects in Unity
The concept of creating or destroying is something we all are familiar with, let’s talk a little bit about how you can do it in Unity.
Creation / Instantiation
The instantiate method takes at minimum an object that you want to copy and returns a clone of it. Instantiate(enemyPrefab);
Since I don’t want them to always spawn in the same place, I use one of the other overrides (variants of the method) that lets me set a position for the clone to appear, this also requires me to set the rotation of it. Of course, for my 2D game that’s not a big issue, but for 3D that could make a world of difference. In addition, to keep things tidier in the hierarchy, I’m setting all the clones to be put as a child object of one specific Gameobject.
Instantiate(_enemyPrefab, GetRandomSpawnPosition(), Quaternion.identity, _enemyContainer);
If I needed to do something with the newly created clone, I could cache it to a variable and use that to call methods and so on:
GameObject go = Instantiate(_enemyPrefab, GetRandomSpawnPosition(), Quaternion.identity, _enemyContainer);
Enemy enemy = go.GetComponent<Enemy>();
// enemy.MethodName();
Destroy
Destroying things is even easier, just like it often can be in real life 😅
The destroy method takes one object as its first parameter, with an optional second one, a floating-point number to represent time in seconds. Destroy(enemyGameObject);
/ Destroy(enemyGameObject, 1.5f);
If there was an animation you’d want to have finish playing before removing the enemy, setting a time for it to wait, before the object is actually destroyed is one way to do it.
The destroy method is used to remove a GameObject, an asset, or a component.