2
votes

I am trying to use Reflection (first time for me and I have looked through many of the other answers for this error and not found one that works for me)

Here is the Calling Method

void OnMouseDown(){
    string CardName = "GoldFate";

    Type classType = Type.GetType(CardName);
    Debug.Log ("Type: " + classType);

    MethodInfo theMethod = classType.GetMethod("Resolve"+CardName);
    Debug.Log ("MethodInfo: " + theMethod);

    theMethod.Invoke(this, null);
}

Here is the target:

public class GoldFate {
    public void ResolveGoldFate(){
        Debug.Log ("We got to Gold Fate");
    }
}

The output this generates is:

Type: GoldFate

MethodInfo: Void ResolveGoldFate()

TargetException: Object does not match target type. System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:236) System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MethodBase.cs:115) FateCardManager.OnMouseDown () (at Assets/Scripts/Card Manipulation/FateCards/FateCardManager.cs:53) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)

I do not get to the Debug Message obviously

Thanks in advance

2

2 Answers

5
votes

I think your problem lies here in this line: theMethod.Invoke(this, null);. Here the this needs to be an instance of GoldFate class. Once you have ensured that, I think you'll be able to invoke the method successfully.

2
votes

The above solutions, streamlined:

var myClass =   new MyClass();

var method =    myClass.GetType().GetMethod( "MyMethod" );
if ( method != null )
    method.Invoke( myClass, null );

Thanks to your answers I was able to get this working in my code! <3