1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityEditor.Editorの意外な挙動について

Last updated at Posted at 2015-06-28

UnityEditor.Editorの挙動について

カスタムインスペクタを作成するときに使用するUnityEditor.Editorについて注意しなければいけない挙動をまとめてみます。

インスペクタが切り替わるたびにオブジェクトは再生成

UnityEditor.Editorはいつコンストラクタが呼ばれるかつまりいつ新しいオブジェクトになるかですが、インスペクタが一回でも切り替われば新しいオブジェクトになります。

次の画像はこんなコードを入れたカスタムインスペクタのスクリプトをアタッチしたGameObjectを選択して外して選択した図

こんなコード

Inspector
    public class Inspector : UnityEditor.Editor
    {
        public Inspector() {

            Debug.Log("ctor called");
        }
    }

左から選択1回め外して2回めの図です・

first.png

"ctor called"が2回出力されているのがわかります。
つまりUnityEditor.Editorは使い捨ての挙動になるので例えば一時的にインスペクタ側に値を保持したりするのは危険になります。

うーんでもインスペクタ側に保持したいときたまにあるぞ・・・

#if UNITY_EDITOR で本体コード側に書いてもいいけどコード汚くなるよなぁっておもいます(しょうがない気はする)
余談ですが本体コード内でUnityEditorのコード使いたいときは、using UnityEditor;は#if UNITY_EDITORでくくらないとコンパイル通らなくなるゾ!

コンストラクタ内ではtargetはnull

インスペクタが参照しているターゲットを表すEditor.targetですが、こいつはコンストラクタではまだnullです。
OnInspectorGUIの前のどっかで初めて代入されるみたいです。

で、このタイミングでなんか初期化処理的なのをしたいなーと思っても初期化関数みたいなのはないみたいです。
正確にはpublic void Initialize(UnityEngine.Object[] targets);っていうのが定義されているのですけどこれのドキュメントなんてないので内部のどっかですね!

やりたいならOnInspectorGUIの最初の1回を取るしかないのかなぁ・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?