Before I post any pseudo-code, I do entirely agree with what @DMGregory has posted. If your code knows enough to know the method, there's probably a cleaner way to do it. Interfaces are a nice and clean approach (as posted by @LinkWindcrafter in another answer here).
Now, if you've explored all reasonable options and there's simply no other alternative... I think you may be looking for the Type.GetMethod(String, BindingFlags) feature.
Here's some quickly hacked together pseudo-code:
public struct OwnerAndMethod
{
public object Owner { get; private set; }
public MethodInfo Method { get; private set; }
public void Invoke ()
{
Method.Invoke (Owner, null);
}
public OwnerAndMethod (object owner, MethodInfo method) : this ()
{
Owner = owner;
Method = method;
}
}
private static List<OwnerAndMethod> GetMethodsFromComponentsViaReflection (IList<object> objects, string methodName)
{
List<OwnerAndMethod> ownerAndMethods = new List<OwnerAndMethod> ();
for (int i = 0; i < objects.Count; i++)
{
MethodInfo method = objects[i].GetType ().GetMethod (methodName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
ownerAndMethods.Add (new OwnerAndMethod (objects[i], method));
}
}
return ownerAndMethods;
}
private void Start ()
{
MonoBehaviour[] components = transform.GetComponents<MonoBehaviour> ();
List<OwnerAndMethod> methods = GetMethodsFromComponentsViaReflection (components, "Hey");
foreach (OwnerAndMethod method in methods)
{
method.Invoke ();
}
} method.Invoke ();
}
}
There's obviously so many possible exceptions that can be thrown from this code, so take this as a reference and not so much an exact way of doing it.
I hope this helps. Good luck!
switch(string)and what you want is dynamic exploring of all methods on all scripts? \$\endgroup\$