[4.6 - UI] Calling function on button click via script

So I’ve been trying to mess around with the UI in 4.6/5.

I’m wondering how to call a function in a C# script when a UI Button has been clicked, like when trying to advanced some text been shown. I just need to find out how to check if the button has been clicked.

I have imported the UnityEngine.UI and UnityEngine.EventSystems, not sure how to use it though.

There are two ways around it:

  • Add listeners in the editor - if your button is placed in the editor and always does the same thing, then this is easiest. Select the button and find the Button component. At the bottom, there is an On Click() field. There you can select and object, script component and function on that script (function must be public), you can also add values to pass.

  • Add listeners in script:

    [SerializeField]
    private Button MyButton = null; // assign in the editor

    void Start()
    {
    MyButton.onClick.AddListener(() => { MyFunction(); MyOtherFunction(); });
    }

I was stuck at a similar problem recently. I had multiple buttons added via script and each of them should call a function with another parameter. There was a lot of trouble because everytime only the last button in the list called the function instead of the other one i really wanted to. So my trick was to add a short script (only with my listener and the variable) to each button Prefab. So if the buttons are created there is no Problem with the sharing of the listeners.

I hope i could save someone a little bit of time ^^