寻找方法的实例

Jer*_*ski 2 c# reflection

这个问题是针对Unity3D的实用程序脚本的,但问题只在于C#;

我提供的脚本字符串(onClickCallbackPath)看起来像" GameObjectName.ComponentTypeName.CallbackDelegateName ".

查找GameObject和Component不是问题,但请看一下这段代码:

    string[] ss = onClickCallbackPath.Split ("." [0]);
    Transform onClickTarget = Tools.FindDeepChild (transform.root, ss [0]);
    MonoBehaviour[] allComponentsOnTarget = onClickTarget.GetComponents<MonoBehaviour> ();

    foreach (MonoBehaviour mb in allComponentsOnTarget) 
    {
        if (mb.GetType ().Name == ss [1]) 
        {
            MethodInfo[] methods = mb.GetType ().GetMethods (BindingFlags.Public);

            foreach (MethodInfo mi in methods) 
            {
                if (mi.Name == ss [2]) 
                {
                    // And here is how I imagine it to work, and look for something similar...
                    // but of course there is no GetInstance method in MethodInfo
                    Action a = (Action) mi.GetInstance(mb);
                    break;
                }
            }

            break;
        }
    } 
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我需要找到一个Action类型的对象(我确定它是具有正确签名的方法),在我找到的MonoBehaviour中.

我试着看看所有的MethodInfo属性都有类似我正在寻找的东西,也尝试在网上找到解决方案(也在这里SO)但没有成功.我打赌我找到解决方案的问题只是错误地命名问题.

但我希望你明白我的问题是什么.

任何帮助赞赏.

Lua*_*aan 5

你在寻找什么

(Action)Delegate.CreateDelegate(typeof(Action), mb, mi)
Run Code Online (Sandbox Code Playgroud)