美文网首页unity3D技术分享
unity反射执行方法,MethodInfo和Parameter

unity反射执行方法,MethodInfo和Parameter

作者: 好怕怕 | 来源:发表于2019-02-25 15:56 被阅读69次

解决配置表中配置了一些方法,例如新手引导,剧情等系统,需要配置一些执行的方法字符串,然后利用反射运行方法。

using System;
using System.Reflection;
using UnityEngine;

public class SelectAction
{
    public object OnSelect(object[] value)
    {
        Debug.LogError("OnSelect:" + value[0]);
        Action<string> action = value[1] as Action<string>;
        action.Invoke(value[0].ToString());
        return value;
    }
}

public class ReflectionMethod : MonoBehaviour
{
    public void Awake()
    {
        Action<string> action = OnSelectFinish;
        // 支持多参数
        ExcuteMethod(new SelectAction(), "OnSelect", "啊哈哈哈哈哈哈", action);
    }

    private void ExcuteMethod(object obj, string methodName, params object[] parameterValues)
    {
        MethodInfo method = obj.GetType().GetMethod(methodName.Trim());
        if (method == null)
        {
            Debug.LogError("方法不存在!");
        }
        ParameterInfo[] parameters = method.GetParameters();
        if (parameters.Length > 0)
        {
            object[] pars = new object[] { parameterValues };
            var info = (method.Invoke(obj, pars)) as object[];
            Debug.LogError("回调:" + info[0]);
        }
        else
        {
            Debug.LogError("没有方法!");
        }
    }

    private void OnSelectFinish(string info)
    {
        Debug.LogError("OnSelectFinish:" + info);
    }
}

相关文章

网友评论

    本文标题:unity反射执行方法,MethodInfo和Parameter

    本文链接:https://www.haomeiwen.com/subject/cojgyqtx.html