- Home /
How to add callback for button press to a private function (New UI)?
I am aware that in the new UI you can only add callbacks for public functions for buttons, however I was wondering if it's possible to flag my function in some attribute that will allow me to hook it up in the editor (without hooking it manually in the code)?
Thanks!
It is not possible to call a private function outside it's scope (in this case class) . It might be possible if you use reflection (I've never done this, the private methods are private for a reason) but I wouldn't recommend it. Also, $$anonymous$$ake a public "wrapper" method that calls the private function inside if you want a compromise and a quick solution.
@CodinRonin - that is incorrect, Unity does this a lot with reflection (Send$$anonymous$$essage for example) and I've seen it happen in a lot of places (ie. old animation system) - I am wondering if it's possible to use private functions in the new UI Event System
If you want to use a private method outside of its class then you have a design problem as it should be public.
I doubt you saw some private members being used outside of their class in Unity since, again, that would be bad design and I doubt Unity hires bad design programmers.
What you may have seen is internal variables which makes them available within the UnityEngine namespace but not available from your scripts.
Answer by iamvishnusankar · Jan 27, 2015 at 07:02 PM
Here's the solution for you.
Create a custom EventManager class to handle your button click events.
//Custom Event manager class
public class MyEventManager : MonoBehaviour { public delegate void ClickedAction(); public static event ClickedAction onCliked; public void _ButtonClick() { onCliked (); } }
Subscribe to the clicked event from any other script and you can execute private function. Make sure you've properly subscribed and unsubscribed from custom event using OnEnbale() and OnDisable() to avoid multiple instances.
//Test script 1
public class Test1 : MonoBehaviour { //Subscribe to event onEnable void OnEnable() { MyEventManager.onCliked += MyTest1; } void MyTest1 () { Debug.Log ("Test 1 called"); } //Unsubscribe to event onDisable void OnDiable() { MyEventManager.onCliked -= MyTest1; } }
//Test script 2 public class Test2 : MonoBehaviour { //Subscribe to event onEnable void OnEnable() { MyEventManager.onCliked += MyTest2; } void MyTest2 () { Debug.Log ("Test 2 called"); } //Unsubscribe to event onDisable void OnDiable() { MyEventManager.onCliked -= MyTest2; } }
Hope this help! Cheers :)