Wibble Wibble - 1 year ago 103
C# Question

C#/Unity - Reflection - Object Does Not Match Target Type

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download