![]() |
VOOZH | about |
A delegate is a variable that holds a reference to a method. An event uses delegates to notify multiple scripts when something happens.
Events and delegates in Unity are used to enable communication between different scripts in a flexible and decoupled way.
Without events:
With events:
The coin doesn't need to know who is listening. You can add or remove listeners without changing the coin script.
This script fires an event when player touches the coin. Any script listening will respond.
OnCoinCollected?.Invoke() calls all listening methods. The ? checks if any listeners exist.
This script subscribes to the coin event and adds score when coin is collected.
+= subscribes to event. -= unsubscribes - important to prevent memory leaks.
Sometimes you need to pass data like score value or damage amount.
Example: Enemy
ScoreManager:
Health script fires events when health changes or player dies.
Example: Health
UI script listens and updates health bar.
UnityEvent can be assigned in Inspector without writing code.
In Inspector, you can drag GameObjects and select methods to call.