You can destroy a GameObject in Unity using the Destroy()
function. This function is provided by the UnityEngine
namespace and takes a single argument: the GameObject you want to destroy.
Here's how you can use it:
- Directly:
Destroy(gameObject);
This will destroy the GameObject the script is attached to.
- By reference:
GameObject targetObject = GameObject.Find("MyObject"); Destroy(targetObject);
This will find a GameObject named "MyObject" in the scene and destroy it.
You can also use the DestroyImmediate()
function to destroy a GameObject immediately, without waiting for the next frame. This is useful when you need to destroy a GameObject during the current frame, for example, when responding to user input.
Here are some additional points to consider:
- Delayed destruction:
Destroy(gameObject, 2.0f);
This will destroy the GameObject after a specified delay of 2 seconds.
- Destroying children:
Destroy(gameObject.transform.GetChild(0).gameObject);
This will destroy the first child GameObject of the GameObject the script is attached to.
- Destroying multiple GameObjects:
GameObject[] objectsToDestroy = GameObject.FindGameObjectsWithTag("Destroyable"); foreach (GameObject obj in objectsToDestroy) { Destroy(obj); }
This will find all GameObjects with the tag "Destroyable" and destroy them.
Remember that destroying a GameObject will also destroy all its components.