In this lesson, you will learn how to use UnityEvents to create flexible, Inspector-based connections that allow multiple game objects to react to a single UI trigger without needing hard-coded references.
The Problem: Tight Coupling
When you build a UI, it is tempting to have your button script keep a direct reference to every other system it needs to talk to—like the AudioPlayer, ScoreManager, or UIManager. This is "tight coupling." If you decide to add a new sound effect or remove a menu animation later, you have to open the C# code, modify the references, and risk breaking your build.
The Solution: UnityEvents
UnityEvents allow you to define a "hook" in your code that acts like a broadcast. When an event fires, it doesn't care who is listening or what they do; it simply says, "I have been triggered!" You can then connect any method from any object in your scene directly through the Inspector.
Consider this UIButtonController script:
using UnityEngine;
using UnityEngine.Events;
public class UIButtonController : MonoBehaviour
{
// This creates the list in the Inspector
public UnityEvent OnButtonClicked;
public void TriggerClick()
{
// Broadcast that the event happened
OnButtonClicked.Invoke();
}
}
Configuring in the Inspector
Once you add this script to a button, you will see an "On Button Click" section in the Inspector with a plus (+) icon. Instead of writing code, you drag your AudioSource into the slot and select Play(), then drag your ScoreManager into another slot and select AddPoints().
By decoupling the trigger (the click) from the response (the audio and scoring), your UI becomes modular. You can add, remove, or swap out functionality entirely within the Unity Editor without writing a single extra line of code. This keeps your scripts clean, reusable, and much easier to debug as your UI grows in complexity.
Key Takeaway: UnityEvents allow you to build "plug-and-play" systems where UI interactions trigger logic dynamically, removing the need for scripts to know about the specific systems they are communicating with.