Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Interacting with Sprite and UI Buttons in a Unity Game

TwitterFacebookRedditLinkedInHacker News

When you’re developing a game, whether it be 2D or 3D, you’re going to need to add menus with buttons at some point. These buttons could be as simple as a means to exit the game, or something more complex.

In the Unity game development framework, there are a few ways to accomplish buttons. You could create sprites and interact with them through mouse clicks and keyboard presses, or you could make use of the canvas and UI elements.

In this tutorial, we’re going to look at both options for creating buttons in a game.

Adding 2D Sprite Buttons to a Game

The first approach we’ll explore is using a sprite as a button. Since a sprite is more or less an image with other perks, you can use whatever image as you want to represent the button. Rather than getting fancy in this example, our sprite-based button will be nothing more than a white square.

To get an idea of what we’re going to build, take a look at the following image:

Sprite Button in Unity

Within your Unity IDE, choose GameObject -> 2D Object -> Sprites -> Square from the menu. Next, create a SpriteButton.cs script within your Assets directory. The SpriteButton.cs script should contain the following C# code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpriteButton : MonoBehaviour {

    void OnMouseDown() {
        Debug.Log("BUTTON PRESSED");
    }

}

Once the script is saved, you can either drag the script onto the sprite, or choose to add a new component to the sprite at which point you can select the script.

With the script attached, you can try running the game. You’ll notice that our sprite button does nothing.

The OnMouseDown method does nothing for a sprite until we add a collision box to the sprite.

In the Unity IDE, select the sprite and then choose to add a component. You’ll want to add a Box Collider 2D component to the sprite. If you try running the game again, clicking the button will result in a message being output in the logs.

Let’s explore our other option for on-screen buttons within Unity.

Adding Legacy UI Buttons to a Game

The next approach, my personal go-to, is to use a UI button. We’re going to start by exploring the legacy option before adventuring into the modern way to do business.

Within the Unity IDE, choose GameObject -> UI -> Legacy -> Button from the menu. This will create a button within a canvas as well as an event management system. You’ll probably need to adjust the display of the canvas to your liking, but that is out of the scope of this tutorial.

Here is an example of what my legacy button looks like:

UI Button in Unity

With the UI element added to the game, we need to focus on the script that will power the button. Create a LegacyButton.cs file within your Assets directory. Within the LegacyButton.cs file, add the following C# code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LegacyButton : MonoBehaviour {

    private Button _button;

    void Awake() {
        _button = GetComponent<Button>();
        _button.onClick.AddListener(btnClick);
    }

    void btnClick() {
        Debug.Log("BUTTON PRESSED");
    }

}

How we work with UI buttons is a little different than how we work with sprite buttons. Instead of checking for mouse events we can add a listener to the button itself. When the listener is triggered, we can do a task.

This can all be done without using any collision boxes.

Attach the script to the button and run the game. You should be able to click it and see the message in your logs.

Adding a TextMeshPro Button to the Game

In the previous section we added a legacy button. Even though it’s legacy, I’m not ashamed to admit that it is still what I use. The good news is that we can add a more modern TextMeshPro button and use the same code.

From the Unity IDE, choose the GameObject -> UI -> Button menu item.

Here is the code we just saw:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ModernButton : MonoBehaviour {

    private Button _button;

    void Awake() {
        _button = GetComponent<Button>();
        _button.onClick.AddListener(btnClick);
    }

    void btnClick() {
        Debug.Log("BUTTON PRESSED");
    }

}

If you attach the script to the new button, you should be able to click the button and see the output in the logs.

Assigning Button Functions from the Unity Inspector

In the examples with the TextMeshPro button and the legacy button, we attached a script directly to the button which had its own listener information. There is an alternative method to executing functions on click with a button.

Let’s start by creating another script. We’ll call it MainController.cs and save it to the Assets directory. This MainController.cs file will contain the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainController : MonoBehaviour {

    public void ButtonClick() {
        Debug.Log("BUTTON PRESSED");
    }

}

Attach the script to the camera game object within your scene.

Open the inspector for one of your buttons and you’ll notice a section for On Click which allows you to add functions. Add the camera game object and then find the ButtonClick function in the drop down.

As long as your function is public, it should show up in the list and it should be executed when the button is pressed.

Conclusion

You just saw a few options when it comes to adding buttons to your Unity game. All will get the job done, but my personal preference is to use the UI button as most of what I do is more menu and overlay oriented. However, pick whatever makes the most sense to you.

A video version of this tutorial can be found below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

Subscribe

Subscribe to the newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

Support This Site