Unity Inspector中实现按钮调用指定GameObject脚本函数的方法
实现Inspector中选择GameObject并调用脚本函数的UI功能
你的需求是通过UI按钮,调用Inspector中指定GameObject对应脚本的目标函数,下面是具体实现方案:
步骤1:定义可配置的数据结构
先创建一个可序列化的类,用来在Inspector中存储GameObject、脚本引用和要调用的函数名:
using UnityEngine; using System; [Serializable] public class FunctionCallConfig { public GameObject targetObject; public MonoBehaviour targetScript; public string functionName; }
步骤2:修改AvatarSystem脚本
更新你的AvatarSystem,添加配置项并实现点击调用逻辑:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; using System.Reflection; public class AvatarSystem : MonoBehaviour { public Button general; public Button face; public Button hair; public Button eyebrows; public Button clothing; // 对应每个按钮的调用配置,在Inspector中设置 public FunctionCallConfig generalConfig; public FunctionCallConfig faceConfig; public FunctionCallConfig hairConfig; public FunctionCallConfig eyebrowsConfig; public FunctionCallConfig clothingConfig; void Start() { var root = GetComponent<UIDocument>().rootVisualElement; general = root.Q<Button>("general"); face = root.Q<Button>("face"); hair = root.Q<Button>("hair"); eyebrows = root.Q<Button>("eyebrows"); clothing = root.Q<Button>("clothing"); general.clicked += () => CallTargetFunction(generalConfig); face.clicked += () => CallTargetFunction(faceConfig); hair.clicked += () => CallTargetFunction(hairConfig); eyebrows.clicked += () => CallTargetFunction(eyebrowsConfig); clothing.clicked += () => CallTargetFunction(clothingConfig); } /// <summary> /// 通过反射调用目标脚本的指定函数 /// </summary> void CallTargetFunction(FunctionCallConfig config) { if (config.targetObject == null || config.targetScript == null || string.IsNullOrEmpty(config.functionName)) { Debug.LogWarning("请在Inspector中完善调用配置"); return; } // 获取目标函数 MethodInfo method = config.targetScript.GetType().GetMethod(config.functionName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { Debug.LogError($"在脚本{config.targetScript.GetType().Name}中找不到函数{config.functionName}"); return; } // 调用函数 method.Invoke(config.targetScript, null); } }
步骤3:在Inspector中配置
- 将AvatarSystem脚本挂载到包含UIDocument的GameObject上
- 展开每个按钮对应的Config项:
- 选择
Target Object:你要操作的GameObject - 选择
Target Script:该GameObject上挂载的目标脚本 - 输入
Function Name:要调用的函数名称(注意大小写匹配)
- 选择
关键说明
- 反射调用支持公共(public)和私有(private)函数,只要函数名称正确即可
- 如果函数需要参数,可以修改
CallTargetFunction方法,添加参数数组传递给method.Invoke - 配置项做了空值判断,避免空引用报错
内容的提问来源于stack exchange,提问作者LearningJava
相关产品推荐
相关产品推荐

