Unity3D 4.6 UI: get the button and handle the click event in code

12 Dec

In the new Unity3D UI in v4.6, it is much easier to design fancy UI right within Unity without tertiary tools such as NGUI.

One question frequently met is: how to get access the UI elements such as text, button object in code? Here is the tip:


First and as usual, we can get the game object that wraps the button, as shown below, the TreeGrowthAnimation game object is created by clicking GameObject > UI > Button menu item, so we can retrieve the game object using below code:

    var caption = “TreeGrowthAnimation”;
    var go = GameObject.Find(caption);

Next, we can use the GetComponent<> function to retrieve the button object:
    var button = go.GetComponent<Button>();

 image image

To wrap up, we can use below handy function to get the button instance:

   public Button GetButton(string caption)
       var go = GameObject.Find(caption);
       var button = go.GetComponent<Button>();
       return button;

And then we can easily add the button click event handler:

    TreeAnimationButton.onClick.AddListener(() =>
        Debug.Log(“Tree Animation”);

Also remember to import the new namespace: using UnityEngine.UI;

Happy coding!


Posted by on December 12, 2014 in Programming, Unity 3d


Tags: , , , , , , , , ,

2 responses to “Unity3D 4.6 UI: get the button and handle the click event in code

  1. Septian Aji Sanjaya (@SeptianASanjaya)

    March 21, 2015 at 4:43 pm

    Wow amazing tutorial, please can you send me files project in my email sir.


  2. rfnajid

    August 28, 2015 at 10:50 am

    This tutorial helps me a lot. Thanks


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: