0

When I try to run the following code, there is an error on the mi.Invoke line, saying "TargetException: Object does not match target type."

I've seen other answers on SO and they all say it's a problem with the first argument of Invoke being "this" rather then the type itself, which is not the case here.

The MethodInfo creation line and invoke line both use the same variable "type2", but it says they are different. How do I fix this error?

//In this example VoxelType is "ConveyorBelt". This is a class with a public Update method, in the same namespace.
Type type2 = getTypeByName (VoxelType)[0]; //Get voxel type
print (type2.Namespace); //Returns null
print (VoxelType); //Returns ConveyorBelt
print (type2);//Returns ConveyorBelt
MethodInfo mi = type2.GetMethod ("Update");
mi.Invoke (type2, null); //Crashes everytime with TargetException
Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42
Matthew
  • 185
  • 2
  • 12
  • Just FYI: there is really no reason to ever do this in Unity. You're just writing components for a game engine. Honestly, it will never work! – Fattie Nov 26 '16 at 14:08
  • Conceivably you're after this: http://stackoverflow.com/a/36249404/294884 hope it helps – Fattie Nov 26 '16 at 14:08
  • But why are you trying to call the Update function with reflection? Also, where is your `getTypeByName` function? – Programmer Nov 26 '16 at 14:36
  • I'm writing a system to make it much easier to add extra blocks to a Minecraft based game. To add an extra block, a new folder is created in the "Voxels" folder, containing a bunch of art assets, and a new c# file with the same name as the block. When unity loads up the game, it loads up all those files. When the main voxel class gets to update for each block, it needs to find out what to do at update from the relevant c# file for that block name. It therefore searches the namespace for that c# file relevant to that block and runs the Update method from the file. This means none of the --> – Matthew Nov 26 '16 at 15:08
  • --> normal code to be changed to add an extra block. – Matthew Nov 26 '16 at 15:11
  • If there's an easier way to do this, please do mention it! – Matthew Nov 26 '16 at 15:17

1 Answers1

0

The reason it wasn't working was because I was trying to call on a non-static method using the class, as opposed to an instance. The code below fixed it:

Type type2 = getTypeByName(NameOfClass)[0]; //Get voxel type
MethodInfo mi = type2.GetMethod(NameOfNonStaticMethod);
object instance = Activator.CreateInstance(type2);
mi.Invoke(instance, new object[] { Parameters });

It took so long to fix this as c# gave a completely irrelevant excuse for refusing to run.

Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42
Matthew
  • 185
  • 2
  • 12