Search Unity

Method Reference by Name

Discussion in 'Editor & General Support' started by AlexGK, Oct 15, 2015.

  1. AlexGK

    AlexGK

    Joined:
    Jul 31, 2013
    Posts:
    38
    Hello:

    I've been working on a couple custom inspectors for a small event handling system. I want to get references to certain kinds of methods, and be able to select them via editor. So far so good, thanks to XML acting as a database (to get standard event names) and System.Reflection (GetMethod and checking parameters).

    Problem is: I've found no way to call those methods. I've got reference to the GameObject that holds the method, and both the script name and method name (as strings). Invoke won't work for me, because I need to store those methods for later use (acting as delegates/callbacks), and Invoke only seems to call methods right at the moment.

    Any help/ideas?
     
  2. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    Did you try to use System.Reflection for actually invoking the methods?

    Once you get a MethodInfo object, you can, you can call Invoke on it to execute it.
     
  3. AlexGK

    AlexGK

    Joined:
    Jul 31, 2013
    Posts:
    38
    Thanks for the reply. I finally found what I was looking for (thanks to a script from the NGUI guys). So, anyone in the future looking for something like this, here it is:

    Code (CSharp):
    1. //All checks done previously before call
    2. //You want to make sure to send the proper Type, and check the method's name isn't empty and the method itself has a similar structure to MyDelegate
    3. //Limitation: your GameObject can only have one Component of the Type you're sending (maybe storing the Component index somewhere might do the trick)
    4.  
    5. private static MyDelegate GetEventHandler(GameObject _actionGameObject, string _componentType, string _methodName){
    6.     var actionComponent = actionGameObject.GetComponent(_componentType);
    7.     MyDelegate d = System.Delegate.CreateDelegate(typeof(MyDelegate), actionComponent, methodName) as MyDelegate;
    8.     return d;
    9. }
    Invoke() wasn't an option because I needed the reference to the delegate for later use.