- Home /
Answer by DiegoSLTS · May 05, 2019 at 05:41 PM
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).
Thank you . Sorry, I should have specified that it is indeed for the Editor scrip! Thank you for the detailed answer. The 'mode' accessor you spoke of, do I need to reference the "1-6" as you said in order to get the associated method name?
For the mode, you'll do something like (I haven't tested this, but I guess this or something similar will work):
Type[] types = new Type[1];
int mode = serializedProperty.FindPropertyRelative("$$anonymous$$ode").intValue;
switch(mode) {
case 1: types[0] = typeof(void); break;
case 2: types[0] = typeof(Object); break;
case 3: types[0] = typeof(int); break;
case 4: types[0] = typeof(float); break;
case 5: types[0] = typeof(string); break;
case 6: types[0] = typeof(bool); break;
}
Where serializedProperty would be the SerializedProperty of the listener added to the onClick event. It's not hard to get that once you understand how SerializedObjects and SerializedProperties work, but it takes a lot of trial and error to get it right. $$anonymous$$ake sure you set your project to serialize files with "Force Text" so you can see how each property is saven on the .unity file, it'll make things a lot easier.
I see. I'll look into this. Thanks for your help!