先看结果
using UnityEngine;
public class Test : MonoBehaviour
{
[InspectorButton("测试方法1")]
public void Test1()
{
Debug.Log("Test1 Invoke!");
}
[InspectorButton]
public int Test2()
{
Debug.Log("Test2 Invoke!");
return 100;
}
}
目录结构(置于非Editor文件夹中)
文章来源:https://www.toymoban.com/news/detail-512693.html
InspectorButtonAttribute.cs
using UnityEngine;
[System.AttributeUsage(System.AttributeTargets.Method)]
public class InspectorButtonAttribute : PropertyAttribute
{
public readonly string Name;
public InspectorButtonAttribute()
{
}
public InspectorButtonAttribute(string name)
{
Name = name;
}
}
InspectorButton.cs
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();
}
}
文章来源地址https://www.toymoban.com/news/detail-512693.html
到了这里,关于Unity 使方法以按钮的形式在Inspector上的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!