- Home /
Setting Button.onClick with a script in the editor
Hey, although I've seen similar questions asked and answered, I'm still completely stuck. I am trying to use UnityEventTools.AddPersistentListener
to add a listener to a button in an editor script, but I get an uninformative error stating that The class null does not derive from UnityEngine.Object
I have a function that takes an integer input, and want to add it as an onClick listener as you would do in the editor
Here's my current buggy attempt (C#) . g is an int, and OpenMenuOf is a method of EnemyListControlScript
EnemyListControlScript E = GameObject.Find("EnemyListController").GetComponent(); Button btn = myButton.transform.GetChild(0).GetComponent(); UnityEventTools.AddPersistentListener(btn.onClick, new UnityAction(delegate { E.OpenMenuOf(g); }));
Not sure why this doesn't work :( any help would be much appreciated, thanks!
You have a button in your scene and you want it to do something in a script when it is pressed? What do you mean you want to add a listener? When you add a button to your scene it should have everything you need except the part of the script you want it to run.
Answer by Qq0 · Jul 17, 2018 at 04:04 PM
After far too many attempts, I got it working, will post code here in case I can help anyone in a similar situation :/
int g = yourInteger;
//E = yourInstanceOfTargetComponent
Button btn = yourButtonComponent;
System.Type[] arguments = new System.Type[1];
arguments[0] = typeof(int);
System.Reflection.MethodInfo myInfo = UnityEvent.GetValidMethodInfo(E, "OpenMenuOf", arguments);
UnityAction ua = System.Delegate.CreateDelegate(typeof(UnityAction), E, myInfo) as UnityAction;
UnityEditor.Events.UnityEventTools.AddIntPersistentListener(btn.onClick, ua, g);
Your answer
![](https://koobas.hobune.stream/wayback/20220612170754im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Assigning a function with a parameter to buttons in for loop with a temp variable 1 Answer
Unity UI dynamic Buttons 4 Answers
Problem with onClick.AddListener 1 Answer
add delegate to toggle in unity 4.6 UI 2 Answers
Runtime Click Listener Addition 0 Answers