Using Unity Events allows you to create a flexible system for triggering functions on one object in response to actions happening on another object, often configured directly in the Unity editor.
Unity Events provide a powerful way to decouple your code and create modular systems. They allow you to expose callback functions that can be configured visually in the Inspector window, without needing to write complex event handler code or direct method calls between unrelated scripts.
Essentially, a Unity Event acts like a list of actions (function calls) that are performed when the event is triggered.
Setting Up Unity Events in the Unity Editor
You can easily set up responses to existing Unity Events (like button clicks, animation events, or trigger events) or events you define in your own scripts directly within the Inspector. Follow these steps:
- Select the GameObject in your scene that contains the script or component with the Unity Event you want to configure (e.g., a
Button
component, anAnimator
component, or your custom script). - Locate the Unity Event in the Inspector window. These are typically labeled clearly (e.g., "On Click ()", "OnTriggerEnter(Collider)", or a custom name you've given it). It will look like a list with "List is Empty" initially.
- Add a Callback Slot: Select the
+
icon at the bottom right of the Unity Event list. This adds a new slot for a function call that will be triggered by the event. - Assign the Target Object: Drag the
UnityEngine. Object
from your scene's Hierarchy or Project window into the object slot (the first slot, often showing "None (Object)"). This is the GameObject or component that has the script containing the function you want to call. You can also use the small circle icon next to the slot to open the object selector window. - Select the Target Function: Click the dropdown menu next to the object slot (often showing "No Function"). This menu lists all the compatible public functions available on the object or component you assigned in the previous step. Functions are often categorized by the type of component they belong to (e.g., your script name, "Transform", "GameObject").
- You can select functions that take parameters if the Unity Event supports them (e.g.,
OnTriggerEnter
passes aCollider
). Unity Events can also be set up to pass specific primitive types (likeint
,float
,string
,bool
) or even custom objects.
- You can select functions that take parameters if the Unity Event supports them (e.g.,
- Configure Function Parameters (If applicable): If you selected a function that takes a parameter, an input field will appear allowing you to set the value that will be passed to the function when the event is triggered. This is often used for "Dynamic" calls, where the parameter value comes from the event itself (like a
float
value from a slider's OnValueChanged event) or "Static" calls where you provide a fixed value in the Inspector. - Add More Callbacks: You can add more than one callback for the event by clicking the
+
icon again. Each added slot allows you to call another function on potentially another object when the same event is triggered. - Remove Callbacks: To remove a callback slot, select the
-
icon on the right side of the slot.
Using Custom Unity Events in Scripts
To create your own events that other objects can subscribe to via the Inspector, you need to define a UnityEvent
variable in your script.
-
Import the Namespace: Make sure your script includes the necessary namespace:
using UnityEngine.Events;
-
Declare the Event: Declare a public variable of type
UnityEvent
(or a generic version likeUnityEvent<ParameterType>
) in your script. Making itpublic
allows it to be configured in the Inspector.public class MyEventTrigger : MonoBehaviour { // Basic Unity Event (no parameters) public UnityEvent onSomethingHappened; // Unity Event with a parameter (e.g., a float value) public UnityEvent<float> onValueUpdated; // ... other script code }
-
Initialize the Event (Optional but Recommended): Although the Inspector handles serialization, it's good practice to initialize it if you plan to add listeners via code.
void Awake() { if (onSomethingHappened == null) { onSomethingHappened = new UnityEvent(); } if (onValueUpdated == null) { onValueUpdated = new UnityEvent<float>(); } }
-
Trigger the Event: Call the
Invoke()
method on yourUnityEvent
variable whenever the event should occur. If it's a genericUnityEvent<T>
, pass the parameter value.void DoSomethingThatTriggersEvent() { Debug.Log("Triggering the event!"); // Trigger the basic event onSomethingHappened.Invoke(); // Trigger the event with a parameter float value = 10.5f; onValueUpdated.Invoke(value); }
Once you add a script with a public UnityEvent
to a GameObject, the event will appear in the Inspector, and you can configure callbacks for it using the steps described above.
Benefits of Using Unity Events
- Modularity: Decouples the event trigger from the event listener. The object triggering the event doesn't need to know which objects are listening or what functions they will call.
- Editor Configuration: Allows designers or less technical team members to connect game logic visually without writing code.
- Reusability: The same event can trigger multiple functions on multiple objects. The same function can be triggered by multiple different events.
- Ease of Use: Simple API for defining and invoking events in scripts.
Unity Events are a core system in Unity used for many built-in components and are invaluable for creating flexible and maintainable game systems.