Making a Simple Button in Unity

To learn Unity, you also need to learn UI. Buttons are integral part of UI; they are mostly used in menus to help user navigate between scenes. In this tutorial we will learn

  1. How to create a new Button UI
  2. How to call a script based on Button press in Unity

Create a new Button in Unity

Go to the Hierarchy window and click the + sign and select UI button.

This will add a new button to your scene. Along with the button you will have a canvas and an event system.

Button added to the hierarchy window as a child of Canvas.

Canvas is the plane that holds all the UI element and Event system is required to trigger an event when the UI is interacted with.

Select the scene tab and double click on the button game object to zoom in on the button.

Move your button to the required position.

If you select the button and go to the inspector window, you should see an image component and a button component.

You can replace the Source Image of the image component to change the look of the button.

UI image and button component attached to the default button

Now you have successfully created a new button.

The button has a child text game object. If you do not want any text on your button, you can delete this. If you want to change the text, select the text object and edit the content in the inspector window.

Text object attached to a button.

Call a script based on Button press in Unity

To do this you need the following

  1. A public function in a script.
  2. A game object with the script attached.

Let’s create a simple script to display the text “Button Pressed” in the console. If you are not sure how to create one just copy and paste the code below.

using UnityEngine;

public class Button_Press : MonoBehaviour
{
    // public function to be called on button press
    public void button_pressed()
    {
        Debug.Log("Button Pressed");

    }
}

Create a new empty game object by clicking + sign on the Hierarchy window >Create Empty.

Attach the script you created to your empty game object.

Select the button and go to the inspector window. You should be able to see the OnClick() event.

On click event on the button properties

Click on the + sign to add a new event.

Drag and drop the game object with the script to the Object parameter.

Using the drop down select your script and navigate to the public function.

The public function selected for the onclick event.
Play the game and click on the button.

You should see the message displayed on the console.

You have successfully created a UI button and attached a script to it. Next, we will learn about rich text in Unity.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading