Unity/기능구현

[Unity] Inspector에서 함수 실행하기

민트초밥 2024. 8. 14. 14:10

예전에 Ordin Inspector 에셋을 사용했을 때 그 안에 있었던 기능인데 가끔 필요할 때가 있어서 만들어 봤다.

 

 

Odin Inspector and Serializer | 유틸리티 도구 | Unity Asset Store

Use the Odin Inspector and Serializer from Sirenix on your next project. Find this utility tool & more on the Unity Asset Store.

assetstore.unity.com

 

 

 

 

아래와 같이 [Button] Attribute를 추가하면 Inspector 창에 버튼 UI가 추가되고, 버튼을 누르면 해당 함수가 실행되는 구조이다.

 

 

 

 

 

함수에서만 어트리뷰트를 사용하기 위해 AttributeTargets.Method로 설정

using System;

[AttributeUsage(AttributeTargets.Method)]
public class ButtonAttribute : Attribute
{
    public string ButtonName { get; }

    public ButtonAttribute(string buttonName = null)
    {
        ButtonName = buttonName;
    }
}

 

 

 

 

using UnityEngine;
using UnityEditor;
using System;
using System.Reflection;

// MonoBehaviour를 상속받은 모든 스크립트에 대해 Custom Editor 사용
[CustomEditor(typeof(MonoBehaviour), true)]
public class ButtonAttributeEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        // target의 모든 메서드를 가져옵니다.
        MethodInfo[] methods = target.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        foreach (MethodInfo method in methods)
        {
            // 메서드에 [Button] 어트리뷰트가 적용되어있는지 확인
            var buttonAttribute = (ButtonAttribute)Attribute.GetCustomAttribute(method, typeof(ButtonAttribute));

            if (buttonAttribute != null)
            {
                string buttonName = buttonAttribute.ButtonName ?? method.Name;

                // 버튼을 생성하고, 클릭 시 해당 메서드를 호출
                if (GUILayout.Button(buttonName))
                {
                    method.Invoke(target, null);
                }
            }
        }
    }
}

 

 

 

 

※ 실행 예시

 

 

 

 

 

Play Mode에서도 작동한다.

 

 

 

 

 

전체 코드는 아래에서 확인할 수 있습니다.

 

Unity_Practice_Editor/Unity_Practice_Editor/Assets/MethodButtonAttribute at main · mintchobab/Unity_Practice_Editor

Contribute to mintchobab/Unity_Practice_Editor development by creating an account on GitHub.

github.com

 

반응형