Version: 2021.3
public static void Destroy (Object obj, float t= 0.0F);

参数

obj 要销毁的对象。
t (可选)销毁对象前的延迟。

描述

移除 GameObject、组件或资源。

在当前更新循环之后立即销毁或从现在开始 t 秒(如果指定了时间)后销毁对象 obj。 如果 objComponent,则此方法会从 GameObject 移除该组件并将它销毁。 如果 objGameObject,则会销毁该 GameObject、其所有组件以及该 GameObject 的所有变换子项。 实际的对象销毁操作始终延迟到当前更新循环结束,但始终在渲染前完成。

Note: When destroying MonoBehaviour scripts, OnDisable and OnDestroy are called before the script is removed.

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") &amp;&amp; GetComponent<BoxCollider>()) { Destroy(GetComponent<BoxCollider>()); } } }

销毁继承自 UnityEngine.Object 基类。