mercredi 3 février 2021

C# Find a Method by Name and run it (IEnumerator method)

I'm trying to retrieve & run a function inside some other object according to it's name.

So, for example, given the following class:

public class A 
{
public IEnumerator func1()
{
print("function 1");
yield break;}
}

I'm trying to retrieve func1 and run it.

My Attempt:

public static MethodInfo GetMethodByName(object obj, string methodName)
{
    return obj.GetType().GetMethods().FirstOrDefault(m => m.Name == methodName);
}

then:

Startcoroutine((IEnumerator)GetMethodByName(classAObject, "func1"));

ERROR I GET:

"Specified cast is not valid"

Any ideas? Thanks!





Aucun commentaire:

Enregistrer un commentaire