- Home /
How to get parameters of UnityEvent that I set in inspector from script?
I want to get the number 5 that I set in inspector but I find nowhere in my button.onClick. What I eventually to do is to copy (or move) this onClick event to another component in script (execute in editor mode).
I googled GetValidMethodInfo but this doesn't contain parameters.
How can I do this?
Answer by Adam-Mechtley · Feb 08, 2017 at 10:48 AM
The most flexible way to do this is to use SerializedProperty. You may find my answer here helpful, but in short you will do something like this:
// assuming you have a reference to your Button component as m_Button
SerializedObject so = new SerializedObject(m_Button);
SerializedProperty persistentCalls = so.FindProperty("m_OnClick.m_PersistentCalls.m_Calls");
for (int i = 0; i < persistentCalls.arraySize; ++i)
// in this example I'm just logging it
Debug.Log(persistentCalls.GetArrayElementAtIndex(i).FindPropertyRelative("m_Arguments.m_IntArgument").intValue);
When you retrieve the int value in this way, you can use SerializedProperty again on your destination object, or you can use UnityEventTools.AddIntPersistentListener and supply the int value you retrieved.
This is great but a little bit cheaty.. Is it actually "ok" or "legal" to use reflection to get non-visible members? I can find unofficial codes but I'm not sure if I can use it in commercial products. Is there any other way to do this? If not, I'll go with this for sure:)
SerializedProperty is not the same as using reflection. It's actually the means we recommend for people to modify properties in editor scripts, because it automatically handles prefab overrides, dirtying, undo/redo, and so on. It is certainly possible you can get into trouble if e.g., some backing field name changes, but these particular properties have already been through a couple of renames so it is safe and reasonable to assume they will not be changing. The caveat of course is that this is an editor-only class, so you should not use it in runtime code.
Your answer
![](https://koobas.hobune.stream/wayback/20220612110609im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Referencing function in editor 0 Answers
Problem when instantiate button with Onclick.Addlistener 0 Answers
Only certain buttons are playing the sound onclick 0 Answers
Calling preset Button OnClick events from another script 3 Answers
OnClick() animation 0 Answers