You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#如何调用反射获取到的组件Interact方法

Unity射线交互反射调用Interact方法实现

你拿到MethodInfo对象后直接调用Invoke方法即可执行目标方法,以下是修正后的可运行代码,附注意事项:

修正后的核心代码

{
    RaycastHit hit;

    if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, distancia, mask))
    {
        Deselect();
        SelectedObject(hit.transform);
        // 推荐用CompareTag判断标签,性能更好,标签名写错时会直接报错方便排查
        if (hit.collider.CompareTag("Objeto Interactivo"))
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                print(hit.collider);
                print(hit.collider.transform);
                if (hit.collider.TryGetComponent(out MonoBehaviour FoundScript))
                {
                    // 获取Interact方法的MethodInfo实例,默认匹配public类型的实例方法
                    System.Reflection.MethodInfo interactMethod = FoundScript.GetType().GetMethod("Interact");
                    
                    if (interactMethod != null)
                    {
                        // 执行方法:第一个参数是方法所属的组件实例,第二个参数是方法入参数组,无参方法传null即可
                        interactMethod.Invoke(FoundScript, null);
                    }
                    else
                    {
                        Debug.LogWarning($"当前命中对象 {hit.collider.gameObject.name} 的脚本 {FoundScript.GetType().Name} 未定义公开的Interact方法");
                    }
                }
            }
        }
    }
}

关键说明

  • 方法调用规则:MethodInfo.Invoke(方法挂载的对象实例, 方法入参数组)
    • 如果你的Interact方法定义了参数,比如void Interact(int itemCount, string promptText),第二个参数按参数顺序传入object数组即可:interactMethod.Invoke(FoundScript, new object[]{1, "按E交互"})
  • 访问权限适配:GetMethod默认只会查找public级别的实例方法,如果你的Interact是private/protected等非公开方法,需要传入绑定标记修改查找逻辑:
    System.Reflection.MethodInfo interactMethod = FoundScript.GetType().GetMethod("Interact", 
        System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    
  • 更优实现方案:反射存在一定性能开销,且方法名写错时不会在编译阶段报错,推荐用接口实现交互逻辑,更稳定高效:
    1. 先定义通用交互接口
    public interface IInteractable
    {
        void Interact();
    }
    
    1. 所有可交互对象的脚本继承该接口并实现Interact逻辑
    public class LiftButton : MonoBehaviour, IInteractable
    {
        public void Interact()
        {
            // 呼叫电梯的逻辑
        }
    }
    
    1. 射线检测时直接获取接口调用,不需要反射
    if (hit.collider.TryGetComponent(out IInteractable interactTarget))
    {
        interactTarget.Interact();
    }
    

内容的提问来源于stack exchange,提问作者Wonds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 02:24:15