예전에 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
반응형
'Unity > 기능구현' 카테고리의 다른 글
| [Unity] Prefab의 Missing Script 자동으로 삭제하기 (0) | 2024.07.19 |
|---|---|
| [Unity] Table CSV 파일을 ScriptableObject로 변환해보자 (0) | 2024.04.30 |
| [Unity] 게이지바 구현하기 (0) | 2024.02.25 |
| [Unity] 모든 하위 오브젝트의 레이어 변경하기 (0) | 2022.04.19 |
| [Unity] Debug Log를 Text 파일의 형태로 저장하기 (0) | 2022.04.19 |