Unity: Reflections to Invoke Methods in Another Class

I hoped I could dynamically cast a type and call methods from it in C#. However, that appears to be impossible. Nor can you use a variable as a type, even if the variable is one. Using reflections, you can at least instantiate a class using a type as a variable and find and call a method from it. Although it was not wholly applicable in my case, someone might find it useful.

In my scenario, I needed a class to discover another class type assigned to the same GameObject and call a method from within it. I knew that the unknown class will always be the 3rd component in the GameObject, so I could discover it like so:

 

Component[] enemyComponents = gameObject.GetComponents(typeof(Component));

enemyType = enemyComponents[2].GetType();

 

In my scenario, the class type may change, but it will always carry a method called “someFunction”. I can reference the method by calling enemyType.GetMethod("someFunction");.

You might wonder why I wouldn’t just use interfaces for this, but for how my system is set up, it would not be suitable and far clunkier in its implementation. Just trust me on this, I have already tried it. The following is the code snippet that gets the constructor from a Type variable, invokes it, and then invokes a method from it and passing the parameter “yourVariable” through.

 

System.Reflection.ConstructorInfo damageConstructor = enemyType.GetConstructor(System.Type.EmptyTypes);

object enemyClassObject = damageConstructor.Invoke(new object[]{});

System.Reflection.MethodInfo enemyMethod = enemyType.GetMethod("someFunction");

object enemyDamageInvoke = enemyMethod.Invoke(enemyClassObject, new object[]{yourVariable});

 

You can pass as many parameters as needed: new object[]{_param1, _param2, …});
If your method has no parameters, replace the object[] with null. Again, this was not the solution for me, but it is useful to know, regardless.

 

For further reference: https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.invoke?view=netcore-3.1