Destroy(Object, float)
Removes a GameObject, component, or asset.
Read time 2 minutesLast updated 4 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.CoreModule
public static void Destroy(Object obj, float t)
Parameters
Remarks
Destroys the specified object. If a time delay () is specified, destruction occurs after t seconds have elapsed. The timer starts from the moment is called. Actual object destruction is always delayed until after the current Update loop, but always happens before rendering.
tDestroyIf the object is a component, only that component is removed and destroyed. If the object is a GameObject, the GameObject, all its components, and all its transform children are destroyed together.
Once is called, the object is scheduled for destruction after seconds, regardless of whether the script component that called it is later disabled or destroyed.
Destroy(obj, t)tDestroyThe delay parameter is affected by Time.timeScale. If Time.timeScale is set to 0 (for example, if the game is paused), the destruction is delayed until time resumes.
tAdditional Resources: Object.DestroyImmediate
using UnityEngine;public class ScriptExample : MonoBehaviour{ void DestroyGameObject() { Destroy(gameObject); } void DestroyScriptInstance() { // Removes this script instance from the game object Destroy(this); } void DestroyComponent() { // Removes the rigidbody from the game object Destroy(GetComponent<Rigidbody>()); } void DestroyObjectDelayed() { // Kills the game object in 5 seconds after loading the object Destroy(gameObject, 5); } // When the user presses Ctrl, it will remove the // BoxCollider component from the game object void Update() { if (Input.GetButton("Fire1") && GetComponent<BoxCollider>()) { Destroy(GetComponent<BoxCollider>()); } }}
Destroy is inherited from the UnityEngine.Object base class.