LoginSignup
3
2

More than 1 year has passed since last update.

UnityEditor上でGameObjectをUpdateさせる方法

Posted at

はじめに

クラスにExecuteAlways属性をつければUpdateが呼ばれるだろうと思いましたが呼ばれなく、詰まったのでUpdateを呼ばれる方法を備忘録として残したいと思います。

テンプレートコード

using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

[ExecuteAlways]
public class CustomInspectorTemplate : MonoBehaviour {
    void Update() {
#if UNITY_EDITOR
        if (!Application.isPlaying) {
            Debug.Log("EditModeUpdate");
        }
#endif
    }

    void OnRenderObject() {
#if UNITY_EDITOR
        if (!Application.isPlaying) {
            EditorApplication.QueuePlayerLoopUpdate();
            SceneView.RepaintAll();
        }
#endif
    }


#if UNITY_EDITOR

    [CustomEditor(typeof(CustomInspectorTemplate))]
    public class CustomInspector : Editor {
        public override void OnInspectorGUI() {
            base.OnInspectorGUI();
        }
    }
#endif
}

解説

ExecuteAlways

Editor上でもAwake,Start,Updateなどを呼ぶようにするための属性です。
以前はExecuteInEditModeが使われていたらしいのですが、PrefabModeの対応などから現在ではExecuteAlwaysが推奨されているようです。

OnRenderObject

EditorModeではUpdateは毎フレーム呼ばれないので、代わりに描画ごとに呼ばれる関数を使用して、

EditorApplication.QueuePlayerLoopUpdate();

を呼び出すことでUpdateを呼ばれるようにして、

SceneView.RepaintAll();

でシーンを再描画するようにします。

OnRenderObject以外にも、OnDrawGizmosを使用することでも実現できました。
(SceneViewのGizmosがOnになっていないとUpdateされませんが)

CustomInspector.OnInspectorGUI

UpdateをEditorModeで呼び出したい時には、インスペクターの拡張も考えられるので、
テンプレートに入れています。

3
2
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
3
2