0
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?

【Unity】Editor.CreateCachedEditorを使ってInspectorで使えるEditor拡張を作った。

Posted at

完成系

Transform

image.png

ScriptableObject + ScriptableObject内のTransform

image.png

実装

実装に当たって3構成で作っています。

  1. タイトルバー
  2. キャッシュエディター ← 本命
  3. 区切り線

タイトルバー

image.png

タイトルバーの作成には以下の2つがあります。

EditorGUILayoutの場合、表示位置の設定ができません。(変数の下に自動的に表示される仕組みになっています。)

今回はEditorGUILayout.InspectorTitlebarの内部で行われている処理にプラスして
インデントを追加したかったのでEditorGUI.InspectorTitlebarを使用しました。

Rect rect = GUILayoutUtility.GetRect(GUIContent.none, new GUIStyle("IN Title"));
// インデント
rect.x += _indentLevel; 
rect.width -= _indentLevel;

UnityEngine.Object targetObject = property.objectReferenceValue;
_isFoldoutOpen = EditorGUI.InspectorTitlebar(rect, _isFoldoutOpen, targetObject, true);

キャッシュエディター

image.png

今回の肝。Editor.CreateCachedEditor を使用しています。
タイトルバーが展開されているときに表示しています。

Editor.CreateCachedEditorの引数targetObjectの型はUnityEngine.Objectなので
TransformやRigidbody、ScriptableObjectなどが入りますが、
ScriptableObjectのみを対象としてもいいかもしれません。

if (_isFoldoutOpen)
{
    EditorGUI.indentLevel++;

    // キャッシュされたエディターを作成
    Editor.CreateCachedEditor(targetObject, null, ref _editor);

    // 最後のキャッシュされたエディターのインスペクターGUIを描画
    _editor.OnInspectorGUI();

    // 変更を確認し、必要に応じてシーンを再描画
    using var changeCheck = new EditorGUI.ChangeCheckScope();
    if (changeCheck.changed)
    {
        SceneView.RepaintAll();
    }

    EditorGUI.indentLevel--;
}

区切り線

image.png

キャッシュエディターが表示されているとき、どこで終わっているかがわかりにくいため
区切り線を付けました。
そのため、タイトルバーが展開されているときに表示しています。

if (_isFoldoutOpen)
{
    // 区切り線を追加
    GUILayout.Space(1f);
    Rect lineRect = EditorGUILayout.GetControlRect(false, 2f);
    lineRect.x += _indentLevel;
    lineRect.width -= _indentLevel;
    EditorGUI.DrawRect(lineRect, LineColor);
}

GUILayout.Space(15f);

終わりに

基本的にはScriptableObjectで使える機会があるものではないかと思います。
今回作ったものは、簡単に実装しているため複雑なもの(主に配列)には使えません。
そして今回のEditor拡張を使用する場合、使いやすいやり方としてはカスタム属性を使用する方法が良いのではないかと思います。
自分は以下の画像のように[CachedEditor]を付ければ使えるようにしています。
image.png

0
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
0
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?