以下の内容はhttps://indie-du.com/entry/2021/08/20/104024より取得しました。


Unity : インスペクタに表示させたボタンから任意の関数を実行する

下のようなかんじでインスペクタにボタンを表示させ、

f:id:sugar_affordance:20210820102859p:plain

押したときに MonoBehaviour の任意の関数を実行させる。

MonoBehaviour のスクリプトを作成

スクリプトの OnButtonClickInInspector を実行させたいとする。

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

public class ButtonExample : MonoBehaviour
{

    public void OnButtonClickInInspector()
    {
        Debug.Log("インスペクタでボタン押された");
    }
}

Editor を継承したスクリプトを作成

まずプロジェクトウインドウで Editor フォルダがあるか確認、なかったら作る。
この中に作成したスクリプトは Unity エディタのプラグインとして実行されるようになる。

そしたら Editor クラスを継承させたスクリプトを作成。

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

[CustomEditor(typeof(ButtonExample), true)]
public class ButtonCustomEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        ButtonExample script = target as ButtonExample;

        if (GUILayout.Button("Action"))
        {
            script.OnButtonClickInInspector();
        }

    }
}

using UnityEditor; は忘れず入れること。

CustomEditor の第二引数をtrueにしないと、ButtonExample を継承したクラスでボタンが表示されなくなってしまうのでとりあえず入れとく。

indie-du.com

カスタムエディター - Unity マニュアル

UnityEditor.CustomEditor - Unity スクリプトリファレンス




以上の内容はhttps://indie-du.com/entry/2021/08/20/104024より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14