📗

【Unity】Button属性:関数をボタンとして表示する

2025/03/06に公開

はじめに

初めての方も、そうでない方もこんにちは!
現役ゲームプログラマーのたむぼーです。
自己紹介を載せているので、気になる方は見ていただければ嬉しいです!

今回は
 Unityの属性で関数をボタンとして表示する
方法について紹介します

https://zenn.dev/tmb/articles/1072f8ea010299

処理全体

ButtonAttribute.csとButtonDrawer.csの2つ作成します。
ButtonAttributeは任意のフォルダに格納します。
ButtonDrawerはEditorフォルダに格納してください。

ButtonAttribute.cs
using System;
using UnityEngine;

[AttributeUsage(AttributeTargets.Method)]
public class ButtonAttribute : PropertyAttribute
{
    /// <summary> ラベル </summary>
    public string Label { get; private set; }

    /// <summary>
    /// コンストラクタ
    /// </summary>
    public ButtonAttribute(string label = null)
    {
        Label = label;
    }
}
ButtonDrawer.cs
#if UNITY_EDITOR
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(MonoBehaviour), true)]
public class ButtonDrawer : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        MonoBehaviour targetScript = (MonoBehaviour)target;
        MethodInfo[] methods = targetScript.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        foreach (MethodInfo method in methods)
        {
            ButtonAttribute attribute = (ButtonAttribute)Attribute.GetCustomAttribute(method, typeof(ButtonAttribute));
            if (attribute == null)
            {
                continue;
            }

            string label = string.IsNullOrEmpty(attribute.Label) ? method.Name : attribute.Label;
            if (GUILayout.Button(label))
            {
                method.Invoke(targetScript, null);
            }
        }
    }
}
#endif

使い方

表示するボタンのラベルを変える場合はButton属性の引数で受け取る
Button属性の引数なしの場合は、関数名で表示されます

Example.cs
using UnityEngine;

public class Example : MonoBehaviour
{
    [Button]
    private void Example1()
    {
        Debug.Log("Example1 - ボタンを押したよ!");
    }

    [Button("例2の関数を実行")]
    private void Example2()
    {
        Debug.Log("Example2 - ボタンを押したよ!");
    }
}


Discussion