LoginSignup
1
0

More than 3 years have passed since last update.

【Unity】Destroy()とDestroyImmediate()を使い分けなくていいようにする

Posted at

はじめに

Unityのエディタ拡張など非再生時に動くものを作ってるとDestroy()DestroyImmediate()を使い分けるのが地味に面倒なので、意識しなくてもいいようにします。

拡張メソッドを足す

ObjectExtensions.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public static class ObjectExtensions
{
    public static void Destroy(this Object self)
    {
#if UNITY_EDITOR
        if (EditorApplication.isPlaying == false)
        {
            GameObject.DestroyImmediate(self);
        }
        else
#endif
        {
            GameObject.Destroy(self);
        }
    }
}
// Before
#if UNITY_EDITOR
if (EditorApplication.isPlaying == false) {
    GameObject.DestroyImmediate(go);
} else
#endif
{
    GameObject.Destroy(go);
}

// After
go.Destroy();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0