Monday, August 12, 2013

Unity 3D: How to Create a Simple Button with NGUI

I use NGUI on an almost daily basis for the majority of my GUI needs. Just like most tools, regardless of their user-friendliness, there is something of a learning curve. This post covers one of the simplest and most-used features of NGUI: making a standard 2D button.

NOTE: This blog post was originally written for NGUI 2.x. It has been updated for NGUI 3.x. If you are still using 2.x for some reason, please either upgrade or contact me and I'll send you the old post.

If you haven't already, hop on over to the Asset Store and download NGUI (full or free). Import the package into your project and we'll get started!

In the toolbar, go to NGUI > Create > 2D UI. This is where we'll create our base NGUI object.


You will now see the "UI Root" object in your hierarchy. This will be the parent of all of the NGUI objects, including the camera used to render the UI, which they've already created for you.

The simplest way to add a button is to add one of the prefabs NGUI provides and customize it to your liking. The button we're going to add is called "Control - Simple Button". You can find it by either searching for "Control" in the Project pane, and selecting it from the items that come up, or by navigating in your Project pane to Assets > NGUI > Examples > Atlases > Wooden. Either way, drag the prefab into the Hierarchy pane. It should come in as a child of "UI Root".


If you hit "Play" now, you'll find you have a nice-looking button that reacts to being hovered over and clicked. Pretty spiffy, but it doesn't really do anything, because we haven't told it to. Let's fix that.

Create a new C# script by clicking "Create > C# script" in the Project pane. Name it "buttonClick". Double-click it to open it in Mono, delete all of the contents of the file, and paste in the following:

using UnityEngine;

public class buttonClick : MonoBehaviour
{
    private int counter = 0;
   
    void OnClick ()
    {
        counter++;
        print ("Clicked " + counter.ToString () + " times.");
    }
}


Drag and drop this script on to the "Control - Simple Button" object in your hierarchy. Whenever an NGUI button is clicked, it calls the "OnClick ()" method, and the code you've placed in that method will execute. Here, we are simply incrementing a counter and displaying the output in the console. If you don't already know, your console output will be displayed at the very bottom of the editor window. You can also view the console in a separate window by going to "Window > Console" or pressing "Ctrl + Shift + C".


A couple of other useful tidbits:

The text on the button is located in a Label under the "Control - Simple Button" object. Select the label and edit the text field in the Inspector to change the text:


If you want to resize the button, don't do so under the "Transform" component in the Inspector! Doing so will lead to ugly, stretched text. Instead, click the "Control - Simple Button" GameObject, and under the UISprite component, change the "Dimensions" values. Make sure that "Box Collider - auto-adjust to match" is checked. This way, whatever you change the image dimensions to, the collider that detects button presses will match.

So now you have a basic button, and you can modify the code to perform any tasks that you may want (exiting the game, saving settings, selecting a level, etc.). You can create several buttons to make a menu as simple or as complex as you need, and move them all around right in the Scene window to create your layout.

7 comments:

  1. Great tutorial! I'm working through it right now.

    ReplyDelete
  2. You might want to update this tutorial to reflect some of the new changes that are in the 3.x release... I'll inform you of any disparities that I find.

    Here's the first:

    When loading fonts, there's now a button next to the font field that reads "Dynamic." When you click on that button, it will give you a small dropdown menu and allow you to choose between "Bitmap," or "Dynamic." You will be unable to load your font while "Dynamic," is selected. You have to actually change it to "Bitmap," in order to add fonts.

    I'll keep you posted! Still an awesome tutorial!!

    ReplyDelete
    Replies
    1. Thank you! I did notice that in a recent update. I'm going to make a few changes to reflect some of the changes that have occurred, and to make it even simpler. The whole point was to get people started in the simplest way possible, so I'm going to try to do the same thing with the newer version. Thanks so much for your feedback!

      Delete
  3. Thank you was looking for exactly this. Didn't realize the way to go was using the existing prefab. Can't wait to stop using OnGUI!

    ReplyDelete
    Replies
    1. Yeah, OnGUI is great when you first start working with Unity, and it's awesome for small projects where you don't have access to better tools. But, in my opinion, it's not adequate for any commercial products unless you put a lot of work into extending it ... at which point NGUI is going to save you a huge amount of time for a small investment anyway.

      Delete
  4. Great tutorial, thanks. How do i do this button hide after click on it? Thanks.

    ReplyDelete
    Replies
    1. You can use SetActive(false) in OnClick(). So something like this:

      void OnClick ()
      {
      this.gameObject.SetActive (false);
      }

      Delete