Destroying gameobjects comes in handy in lot of game scenarios. Be it ammo collection or killing an enemy, destroying the object from the scene is a must. There are many resource guide on how to destroy the gameobject efficiently in Unity. In this tutorial, we will see how to destroy a gameobject in your scene and other efficient ways to avoid garbage builtup
Destroying a gameobject in Unity
You can destroy any object or component using the Destroy function in Unity. Destroy function takes two inputs. One is the gameobject to be destroyed and the other is the time delay in float.
Destroy any gameobject
Destroy(myobj); //Give the name of your gameobject that you want to destroy in place of myobj
Destroy the Gameobject to which the script is attached
Destroy Gameobject with a tag
Destroy the Script in which the code is present
Destroy any component attached to the gameobject
Destroy(GetComponent<Animator>()); //removes the animator component from the gameobject
Delay destruction of an object
Destroy(this.gameobject,10) //destroys the gameobject after 10 seconds
Things to know about destroying gameobjects in Unity
- Do not execute code in the same script after destroying the gameobject.
- Destroy(this), destroys only the script not the gameobject.
- Destroying objects create a lot of garbage that effects performance.
Efficient way to remove object from scene
To reduce the dump created by destroying objects you can simply set the object as inactive. This way you need not instantiate the gameobject when needed, you can just set it to active. You need not worry if you are destroying one or two gameobjects in a scene. The problem comes when you need to instantiate and destroy large number of objects like bullets in an FPS game.