Buttons let users interact with your game or app by clicking. Click events tell your program what to do when a button is pressed.
0
0
Button component and click events in Unity
Introduction
You want the player to start the game by clicking a Start button.
You need a button to open a menu or settings screen.
You want to let users submit a form or confirm a choice.
You want to trigger an action like jumping or shooting when a button is clicked.
Syntax
Unity
using UnityEngine; using UnityEngine.UI; public class ButtonClickExample : MonoBehaviour { public Button myButton; void Start() { myButton.onClick.AddListener(OnButtonClicked); } void OnButtonClicked() { Debug.Log("Button was clicked!"); } }
You need to add the using UnityEngine.UI; namespace to work with UI buttons.
Attach this script to a GameObject and assign the Button component in the Inspector.
Examples
This example uses a short lambda function to print a message when the button is clicked.
Unity
myButton.onClick.AddListener(() => Debug.Log("Clicked with lambda!"));Here, a named function is called when the button is clicked.
Unity
myButton.onClick.AddListener(MyCustomFunction);
void MyCustomFunction()
{
Debug.Log("Custom function called on click.");
}Sample Program
This program waits for the user to click the button and then prints a friendly message to the console.
Unity
using UnityEngine; using UnityEngine.UI; public class SimpleButton : MonoBehaviour { public Button button; void Start() { button.onClick.AddListener(ShowMessage); } void ShowMessage() { Debug.Log("Hello! You clicked the button."); } }
OutputSuccess
Important Notes
Make sure your Button component is linked in the Inspector, or the click event won't work.
You can add multiple listeners to one button if you want several actions on click.
Debug.Log messages appear in the Unity Console window when running the game.
Summary
Buttons let users interact by clicking.
Use onClick.AddListener to run code when a button is clicked.
Attach scripts and assign buttons in the Inspector to connect them.