In this lesson, you will learn how to bridge the gap between your UI elements and your custom C# scripts using Unity’s Event System.
The UI Bridge
When you add a Button or a Slider to your scene, they don't automatically know what your game scripts are doing. To make them "talk" to each other, we use the Event System. Think of this as a mail delivery service: your UI component is the sender, the Event System is the post office, and your custom script function is the recipient waiting for the message.
Configuring the Interaction
To connect a button to your code, you need three things:
- A UI Object (like a Button) in your Canvas.
- A Custom Script with a
publicmethod. - The Inspector's "On Click" list.
Let’s say you have a script called GameManager with a function to reset the game:
public class GameManager : MonoBehaviour
{
public void ResetGame()
{
Debug.Log("Game has been reset!");
}
}
To link this, select your Button in the Hierarchy. In the Inspector, find the Button (Script) component and look for the On Click () section. Click the + button. Drag the GameObject containing your GameManager script into the empty "Object" slot. Finally, click the dropdown menu that says "No Function," navigate to your script name (GameManager), and select the ResetGame() method.
How it Works
When a player clicks the button, the Event System detects the mouse interaction. It looks at the "On Click" list you configured, finds the GameManager instance, and calls the ResetGame() function automatically. This same pattern applies to Sliders, but instead of "On Click," you use the "On Value Changed" event, which passes a float value from the slider directly into your method. This allows you to influence your game logic without the UI needing to know exactly how the rest of your system works.
Key Takeaway: The Event System acts as a messenger, allowing UI components to trigger public functions in your scripts via the Inspector's event lists without requiring complex manual references.