C Sharp Events
# Events
used to decouple various systems and clean up your code.
Just a way to say something happened without caring who listens or responds.
Events fundamentally are made up of two things…
Publishers | Subscribers |
---|
# Publishers
Publishers can publish an event that can be subscribed to my zero or multiple things.
The publisher does not know or care about the subscribers
!! This ties into clean coding principles and design patterns like MVP. The idea behind these types of things are to separate parts of the code, like the logic from the visuals. Create Reusable code!
There are many ways to do events in c# and a few more in unity.
first you need to declare an event type in the code.
|
|
The above throws a null error. Remember to check for null beforehand. checked if null - verbose
|
|
The syntactical sugar method to shorten the null check is more often used these days.
|
|
EventHandler is a simple Delegate with two fields. Is customary to use the work on before the event.
! Remember that the event is a delegate with fields. Easy to forget because the declaration often doesn’t show it.
EventHandler is the c# class that handles events. Make sure you use system
# Subscribers
The subscriber need to match the signature of the event. This means it needs to accept and return the same types of data.
! The concept of signatures is used in other parts of C# like interfaces.
|
|
Then, in order to access the event, we need to subscribe. Subscribing usually happens when you bring the object into memory and you should unsubscribe when you unload the object. often in the onenable and ondisable methods.
The syntax for subscribing uses the following
|
|
|
|
|
|
The above is still just in one class. The real benefits are when we listen from somewhere else.
In this case we just need references to the right object.
# EventArgs
Eventargs is the standard way to pass more information through the event.
The standard process is a bit verbose.
first we need to make a class the derives from eventargs.
|
|
Once we define the fields in the custom class. We need to add the type to the evenhandler with <>.
|
|
Then in the event subscriber you need to make sure to match the signature.
|
|
You do not need to use eventhandler, event’s work in other ways.
We can define our own delegate to act as our event handler.
|
|
Delegates are essentially function signatures
Now we can make an event of the same type as our delegate.
|
|
we can fire off this event in the same way as the other events.
|
|
And we subscribe in same way too.
|
|
# Actions
we can also use the Action event type. Action is just a delegate that returns void.
|
|
Action also has a generic version.
|
|
we fire of the event in the same way.
|
|
and we subscribe the same way
|
|
# Unity Events
These are show in the editor
|
|
Invoked the same as the others.
|
|
This will show up in the inspector
! These can only take one argument in the editor.