FishPlayer

一个喜欢摸鱼的废物

0%

UnityEditor EasyButton 简易编辑器按钮

一个比较简单但是方便的东西

这是啥

我们平时些写了一些函数在MonoBehavior里想测试,这边可以整一个特性放在需要快速调用的方法上(限于无参数的函数)。
这边可以做一个编辑器的按钮,直接放在MonoBehavior的组件面板上。

上代码

先定义我们需要的这个特性,既然是做个按钮,那就叫Button好了。那么这个特性就应该叫做ButtonAttribute。

1
2
3
4
5
6
7
8
9
[AttributeUsage(AttributeTargets.Method)]
public class ButtonAttribute : Attribute
{
public string m_methodName = string.Empty;
public ButtonAttribute(string methodName)
{
m_methodName = methodName;
}
}

既然我们要在Inspector面板上加东西,那我们也要操作一下Inspector面板。
我们做一个CustomEditor面板给我们的MonoBehavior,这个面板会作用于所有的MonoBehavior。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[CustomEditor(typeof(MonoBehaviour), true), CanEditMultipleObjects]
public class BaseEditor : Editor
{
private Type m_targetType = null;

public override void OnInspectorGUI()
{
// draw default stuff
base.OnInspectorGUI();

if (null == m_targetType)
m_targetType = target.GetType();

while (m_targetType != null)
{
// try find member function and static function :)
MethodInfo[] methods = m_targetType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var method in methods)
{
ButtonAttribute button = method.GetCustomAttribute<ButtonAttribute>();
if (button != null && method.GetParameters().Length > 0)
{
EditorGUILayout.HelpBox("ButtonAttribute: method cant have parameterz.", MessageType.Warning);
}
else if (button != null && GUILayout.Button(button.m_methodName))
{
method.Invoke(target, new object[] { });
}
}
m_targetType = m_targetType.BaseType;
}

}
}

然后新建一个MonoBehavior脚本,试试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ToxicTester : MonoBehaviour
{

[Button("try exec public method")]
public void ExecPublicMethod()
{
Debug.Log("try exec public method wa");
}

[Button("try exec protected method")]
protected void ExecProtectedMethod()
{
Debug.Log("try exec protected method wa");
}


[Button("try exec private method")]
private void ExecPrivateMethod()
{
Debug.Log("try exec private method wa");
}

[Button("try exec public static method")]
public static void ExecPublicStaticMethod()
{
Debug.Log("try exec public static method wa");
}

}

效果如图