如何在Unity Inspector中为ScriptableObject引用其他类的静态函数
在ScriptableObject的Inspector中引用静态函数并触发调用的可行方案
一、核心结论:完全可行
不用依赖第三方插件也能实现,Unity本身提供了原生机制,也可以通过自定义编辑器扩展搞定。
二、具体实现方案
1. 扩展Unity原生UnityEvent支持静态方法
Unity的UnityEvent默认只能绑实例方法,但加几行编辑器代码就能让它显示静态方法选项:
- 在你的
Attack类里加UnityEvent字段:public class Attack : ScriptableObject { public UnityEvent onAttackTriggered; } - 写自定义编辑器代码:
触发事件时直接调用[CustomEditor(typeof(Attack))] public class AttackEditor : Editor { public override void OnInspectorGUI() { serializedObject.Update(); var eventProp = serializedObject.FindProperty("onAttackTriggered"); EditorGUILayout.PropertyField(eventProp); // 强制UnityEvent编辑器显示静态方法选项 var eventDrawer = Editor.CreateEditor(eventProp); eventDrawer.OnInspectorGUI(); serializedObject.ApplyModifiedProperties(); } }onAttackTriggered.Invoke()就行,Inspector里能直接选静态方法。
2. 自定义轻量静态函数引用
如果想搞更简单的实现,自己写个序列化类存静态函数信息,用反射调用:
- 定义存储类:
[System.Serializable] public class StaticFunctionReference { public string className; public string methodName; public void Invoke() { var type = Type.GetType(className); if (type == null) return; var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public); method?.Invoke(null, null); } } - 在
Attack里加字段:public class Attack : ScriptableObject { public StaticFunctionReference onAttack; } - (可选)写个PropertyDrawer优化Inspector,避免手动输字符串出错:
触发时调用[CustomPropertyDrawer(typeof(StaticFunctionReference))] public class StaticFunctionDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); var classNameProp = property.FindPropertyRelative("className"); var methodNameProp = property.FindPropertyRelative("methodName"); classNameProp.stringValue = EditorGUI.TextField(new Rect(position.x, position.y, position.width/2, position.height), "类名", classNameProp.stringValue); methodNameProp.stringValue = EditorGUI.TextField(new Rect(position.x+position.width/2, position.y, position.width/2, position.height), "方法名", methodNameProp.stringValue); EditorGUI.EndProperty(); } }onAttack.Invoke()即可。
3. Unity 2021+直接用SerializableCallback
2021及以上版本的Unity自带SerializableCallback,不用写额外编辑器代码就能绑静态方法:
- 在
Attack类里声明:
直接在Inspector里选静态方法,触发时调用using UnityEngine.Events; public class Attack : ScriptableObject { public SerializableCallback onAttackTriggered; }onAttackTriggered.Invoke()。
三、关于UltEvents的替代建议
如果UltEvents在最新LTS版本兼容性拉胯,除了上面的原生方案,还可以:
- 去UltEvents的仓库或Asset Store页面看看有没有适配新版本的更新;
- 换用其他轻量事件插件,比如
EasyEvents,或者直接用Unity原生事件系统凑合用。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

