DestroyImmediate(Object, bool)
Destroys the specified object immediately. Use with caution and in Edit mode only.
Read time 1 minuteLast updated 6 days ago
Definition
- Type: Method
- Namespace: UnityEngine
- Assembly: UnityEngine.CoreModule
public static void DestroyImmediate(Object obj, bool allowDestroyingAssets)
Parameters
Remarks
DestroyImmediateDestroyIn runtime code, use Object.Destroy instead. This call marks the object for destruction at the end of the current frame, which is safer and prevents many common issues. If you only want to deactivate a GameObject, use GameObject.SetActive instead.
Attempting to call during physics trigger/contact events, animation event callbacks, rendering callbacks, or MonoBehaviour.OnValidate() results in an error.
DestroyImmediateUsing with the optional parameter set to can permanently remove assets from your project.
DestroyImmediateallowDestroyingAssetstrueDestroying or removing objects from a collection (such as an array or list) while looping through it can cause skipped elements, out-of-bounds errors, or other unpredictable behavior. This is a general programming risk, not unique to Unity.
Examples
// Select one or more GameObjects in your hierarchy.// Go to the menu: Tools > Destroy Selected GameObjects Immediately.// The selected GameObjects will be deleted from the scene immediately.using UnityEngine;using UnityEditor;public class DestroyImmediateExample{ [MenuItem("Tools/Destroy Selected GameObjects Immediately")] static void DestroySelectedGameObjects() { // Get all selected GameObjects in the scene var selected = Selection.gameObjects; if (selected.Length == 0) { Debug.LogWarning("No GameObjects selected!"); return; } foreach (var go in selected) { // Destroys the object immediately in the editor Object.DestroyImmediate(go); } Debug.Log($"{selected.Length} GameObjects destroyed immediately."); }}