Any way to pass the function of a listener as a string?

137576-helpimage.png

Thank you!

If you’re doing this on runtime you can do that with some UnityBaseEvent methods and Reflection. You can do something like this:

Button b = GetComponent<Button>();
string method = b.onClick.GetPersistentMethodName(0);
Object target = b.onClick.GetPersistentTarget(0);
System.Type[] types = new System.Type[1] {typeof(string)};
MethodInfo info = UnityEventBase.GetValidMethodInfo(target,method,types);
Debug.Log(info.ReflectedType.Name + "." + method);

It’s not perfect since you need to know the argument type of the method, but it creates the same string you want.

I guess you could use more Reflection features to avoid the need of a hardcoded Type, but it gets more complex. You might be able to iterate over all components of the target object, then get all it’s method’s MethodInfo with their ParameterInfo and test if any of them works with UnityEventBase.GetValidMethodInfo.

If you’re doing this on the editor you can get the SerializedProperty of the onClick event and use that info to get the type and the method name, then you can do something similar to the code above. This is how the events are serialized:

m_OnClick:
m_PersistentCalls:
  m_Calls:
  - m_Target: {fileID: 1535238718}
    m_MethodName: LookAt
    m_Mode: 2
    m_Arguments:
      m_ObjectArgument: {fileID: 0}
      m_ObjectArgumentAssemblyTypeName: UnityEngine.Transform, UnityEngine
      m_IntArgument: 0
      m_FloatArgument: 0
      m_StringArgument: somestring
      m_BoolArgument: 0
    m_CallState: 2

The Mode property is the type of the argument (1 = empty method, 2 = object reference, 3 = int value, 4 = float, 5 = string, 6 = bool).