Making a Simple Button in Unity

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.

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

Select the scene tab and double click on the button gameobject 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.

Unity sale

Now you have successfully created a new 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 gameobject 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
{
    // Start is called before the first frame update
    public void button_pressed()
    {
        Debug.Log("Button Pressed");

    }
}

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

Attach this script to your empty Gameobject.

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

Click on the + sign to add a new event.

Drag and drop the Gameobject with the script to the Object parameter.

Using the drop down select your script and then the public function.

Play the game and click on the button.

You should see the message displayed on the console.

Leave a Reply

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