First, I created a new Unity project – nothing fancy, just a blank 2D project. I like to keep things simple when I’m learning something new. Then, I made a couple of C# scripts. I called one “EventManager” and the other “MyListener”. The names are pretty self-explanatory, I think.
Setting Up the Event
Inside “EventManager”, I created a public event. I used the Action type, which is like a shortcut for making delegates (I still get those mixed up sometimes). It looked something like this:
public static event Action OnMyEvent;
See? Dead simple. This basically sets up a notification that other scripts can listen for.
Then, I made a simple method to trigger the event. I just wanted to see it work, so I threw in a :
public void TriggerMyEvent() {
*("Event triggered!");
if (OnMyEvent != null) {
OnMyEvent();
The if (OnMyEvent != null) part is important. It checks if anyone is actually listening before trying to shout out the event. Prevents errors, you know?
Listening for the Event
Now, over in the “MyListener” script, I wanted to do something whenever the event happened. So, in the Start() method, I “subscribed” to the event:
void Start() {
* += MyEventHandler;
The is the key. It’s like saying, “Hey, when this event happens, also run my method!”
And then I created the method that gets called:
void MyEventHandler() {
*("I heard the event!");
Again, super basic. Just a log message to prove it’s working.
Unsubscribing
One thing my friend told me I should be aware of is “unsubscribing”.Because if you subscribe to an event that could disappear, you should unsubscribe your event, otherwise your event could go missing! It is easily done in the OnDestroy() method:
void OnDestroy() {
* -= MyEventHandler;
See? The only differece is that , meaning that you are unsubscribing now.
Making it Happen
To actually see this in action, I did the following:
Created an empty GameObject in my scene and attached the “EventManager” script to it.
Created another empty GameObject and attached the “MyListener” script.
Added a simple UI button to the scene.
In the button’s “OnClick” event in the Inspector, I dragged the “EventManager” GameObject and selected the “TriggerMyEvent” method.
So, I run the game, click the button, and BAM! In the console, I see:
“Event triggered!”
“I heard the event!”
It works! My “MyListener” script was successfully listening for the event triggered by the “EventManager”.
This was a pretty basic test, but it helped me understand the core concept of events. It’s like setting up a little notification system between different parts of your game. I can see how this could be super useful for things like UI updates, game state changes, and all sorts of stuff.