按键工具

This commit is contained in:
oldpeper 2024-10-22 11:30:53 +08:00
parent b5aa6fd260
commit 2af88c3147
4 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,63 @@
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MonoBehaviour), true)]
[CanEditMultipleObjects]
public class InspectorButton : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var mono = target as MonoBehaviour;
if (mono == null)
return;
var methods = mono.GetType()
.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static
).Where(method =>
Attribute.IsDefined(method, typeof(InspectorButtonAttribute))
).ToArray();
foreach (var method in methods)
{
var attr = method.GetCustomAttribute<InspectorButtonAttribute>();
DrawButton(method, attr.Name);
}
}
private void DrawButton(MethodInfo methodInfo, string methodName)
{
if (string.IsNullOrEmpty(methodName))
methodName = methodInfo.Name;
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(
methodName,
GUILayout.ExpandWidth(true)
))
{
foreach (var targetObj in targets)
{
var mono = targetObj as MonoBehaviour;
if (mono == null)
continue;
var val = methodInfo.Invoke(mono, new object[] { });
if (val is IEnumerator coroutine)
mono.StartCoroutine(coroutine);
else if (val != null)
Debug.Log($"{methodName}调用结果: {val}");
}
}
EditorGUILayout.EndHorizontal();
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9ebbe62bb83f82141a34aeeef4052a8c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,16 @@
using UnityEngine;
[System.AttributeUsage(System.AttributeTargets.Method)]
public class InspectorButtonAttribute : PropertyAttribute
{
public readonly string Name;
public InspectorButtonAttribute()
{
}
public InspectorButtonAttribute(string name)
{
Name = name;
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 39d98e97145b3eb42ba141705d3b7ec9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: