MRが楽しい

MRやVRについて学習したことを書き残す

UnityのInspectorビューにスクリプトの関数を実行するボタンを追加する

本日は Unity の小ネタ枠です。
UnityのInspectorビューにスクリプトの関数を実行するボタンを追加する手順を記事にします。
f:id:bluebirdofoz:20210209231708j:plain

Inspectorビューのカスタマイズ

Inspector ビューをカスタマイズする場合は CustomEditor の属性で拡張するクラスを指定します。
そのうえで Editor クラスの OnInspectorGUI 関数をオーバーライドすることで Inspector ビューをカスタマイズできます。
docs.unity3d.com
docs.unity3d.com

実施例

以下のサンプルシーンを用意しました。
f:id:bluebirdofoz:20210209231745j:plain

[TransformPaste]コンポーネントは設定された2つのオブジェクトのトランスフォームを一致させるスクリプトです。
テスト用に public 関数と private 関数を作成しています。
・TransformPaste.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TransformPaste : MonoBehaviour
{
    [SerializeField, Tooltip("移動元オブジェクト")]
    private Transform Source;

    [SerializeField, Tooltip("移動先オブジェクト")]
    private Transform Destination;

    public void MovePublicMethod()
    {
        Debug.Log("MovePublicMethod");
        MoveMethod();
    }

    private void MovePrivateMethod()
    {
        Debug.Log("MovePrivateMethod");
        MoveMethod();
    }

    private void MoveMethod()
    {
        Source.transform.position = Destination.transform.position;
        Source.transform.rotation = Destination.transform.rotation;
        Source.transform.localScale = Destination.transform.localScale;
    }
}

この[TransformPaste]コンポーネントの Inspector ビューの GUI をカスタマイズするため、以下のスクリプトを作成しました。
・TransformPasteEditor.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEditor;

// 拡張するクラスを指定する
[CustomEditor(typeof(TransformPaste))]
// 継承クラスは Editor を設定する
public class TransformPasteEditor : Editor
{
    // GUIの表示関数をオーバーライドする
    public override void OnInspectorGUI()
    {
        // 元のインスペクター部分を表示
        base.OnInspectorGUI();

        // targetを変換して対象スクリプトの参照を取得する
        TransformPaste transformPaste = target as TransformPaste;

        // public関数を実行するボタンの作成
        if (GUILayout.Button("MovePublicMethodの実行"))
        {
            transformPaste.MovePublicMethod();
        }

        // private関数を実行するボタンの作成
        if (GUILayout.Button("MovePrivateMethodの実行"))
        {
            transformPaste.SendMessage("MovePrivateMethod", null, SendMessageOptions.DontRequireReceiver);
        }
    }
}

f:id:bluebirdofoz:20210209231828j:plain

public 関数を呼び出すボタンは以下のコードです。

// publicメソッドを実行するボタンの作成
if (GUILayout.Button("MovePublicMethodの実行"))
{
    transformPaste.MovePublicMethod();
}

private 関数を呼び出すボタンは以下のコードです。

// privateメソッドを実行するボタンの作成
if (GUILayout.Button("MovePrivateMethodの実行"))
{
    transformPaste.SendMessage("MovePrivateMethod", null, SendMessageOptions.DontRequireReceiver);
}

この状態で Inspector ビューを確認すると、[TransformPaste]コンポーネントにボタンが追加されています。
f:id:bluebirdofoz:20210209231800j:plain

動作確認

シーンを再生して動作確認を行います。
f:id:bluebirdofoz:20210209231842j:plain

ボタンをクリックすると関数が実行され、オブジェクトのトランスフォームが同じになりました。
f:id:bluebirdofoz:20210209231851j:plain

参考ページ

nopitech.com