jeudi 28 juillet 2016

Finding instance of method

This question is for utility script for Unity3D, but the problem is just in C#;

I am providing the script with string (onClickCallbackPath) that looks something like "GameObjectName.ComponentTypeName.CallbackDelegateName".

Finding GameObject and Component is not a problem, but take a look at this code:

    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;
        }
    } 

As you can see I need to find an object of Action type (I am making sure it is method with correct signature), from within the MonoBehaviour I found.

I tried to take a look at all MethodInfo properties to have something like that I am looking for, also tried to find solution in the net (also here on SO) but without success. I bet my problem with finding solution is just wrong naming the problem.

But I hope you understand what is my problem.

Any help appreciated.





Aucun commentaire:

Enregistrer un commentaire