Event in C#

Suleiman Abdullah
2 min readOct 7, 2024

--

Objective: Event in C#.

Lear about delegate before learn event.

Event is enable class or object(publisher) to notify other classes(subscribers) or objects when something of interest occurs.

The class that sends the event is called the publisher and the classes that receive the event are called subscribers.

First we need to create a delegate with method signature.

Boss Script

We create an event using event keyword, and use delegate method signature as type and rename it.

Note: We use static to enable to access it without Instantiate this object.

Now go to the enemy to subscribe to the event, we use plus equal sign to subscribe to the event.

Note: I assume you we have method in enemy to help the boss enemy when his health is below 50 %.

Now go to the boss enemy ,then invoke the event.

Note: Just like delegate, its important to null check if any one is subscribe to our event if no one listen we will get an error.

Best practice when using event.

Make sure to unsubscribe when game object is destroyed or disable .

Best method to unsubscribe in On Disable.

Why you will need to use event over delegate.

Event are more secure because only who subscribe to event will get effect.

No class can modify and event since we can only subscribe unlike delegate.

See you into the next one.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development