Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object does not match target type" when calling methods using string in C#

I'm trying to call a method using a string, but there a problem:

void make_moviment(string mov,Vector3 new_mov){
    GameObject past_panel = GameObject.Find(actual_level.ToString());
    Type t = Type.GetType(past_panel.GetComponents<MonoBehaviour>()[0].GetType ().Name);
    MethodInfo method = t.GetMethod("get_answer");
    method.Invoke(t,new object[] { mov }));   <--- PROBLEM HERE
}

There's always this error "Object does not match target type" related with the last line. Do you have any recommendations?

like image 393
Bernardo Bacalhau Avatar asked Feb 01 '17 01:02

Bernardo Bacalhau


1 Answers

method.Invoke(t,new object[] { mov }));

Is the same as calling

t.WhateverTheMethodIs(mov);

But t is the Type, not the object of that type. You need to pass in the object to call the method on there instead. (Or null if the method is static).

like image 188
Jon Hanna Avatar answered Oct 13 '22 16:10

Jon Hanna