解决配置表中配置了一些方法,例如新手引导,剧情等系统,需要配置一些执行的方法字符串,然后利用反射运行方法。
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);
}
}