Event driven software development is a cornerstone of modern programming. I am much more comfortable with event handlers simply because I find them simpler to set up and use. In actuality… eventhandler objects are a form of delegate… just one that is easier to read I find and to set up.
How does it work?
First make sure that you have access to the System namespace (simply type using System; at the top of your code modules)
Where I have my enum Layer defined, I add an EventArgs class called LayerChangedArgs. This is the information that my event will pass back.
In the file that I created my enum I add an event args class. This is what the EventHandler will be passing back to the subscribers! It simply contains a Layer enum. Note that you cannot pass a Layer enum by itself through the EventHandler, it requires a class object to be passed, so I wrap the enum Layer in the class of type EventArgs.
Next I want to use an event handler.
The bottom of the image shows me creating my EventHandler OnLayerChanged (i highlighted it in yellow). Thats all you have to do to create one.
To use it, I invoke it within my private setter for layerHit. When something sets layerHit (meaning in the code I say layerHit = something as opposed to setting the private variable directly) the private set will run, and if the current value stored in _layerHit does not equal the value being passed to me, I change the value and then if anything is subscribed to OnLayerChanged, I invoke it (which fires it off to the subscribers), making sure that I pass the layer that was hit into my LayerChangedArgs class.
This image shows how I consume this message.
On the Start() method I subscribe to the OnLayerChanged method.
I then created private void Layer_Changed with signature object sender and LayerChangedArgs e. This is the method that will run automatically when the Raycaster class fires off its event.
Here I do the same as in the video and run a switch statement to change the cursor.
This is just an alternate way to using straight up delegates that I use in my day to day development in boring commercial office software, but it works just fine in Unity as well.