Events and EventHandler - an alternate to using the delegate

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.

Events_1
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.

Is there anything more modern?

It would be great if you could share more information about the program itself. I know of several coding packages that could help you a lot more. I am also looking for alternatives to C+. I find it challenging to use. I think I will rely on something more modern for my business plans. I don’t understand why it’s so hard to have an automated feature on your side that helps you create PDFs instantly without the crazy installation of plugins at extra cost. After doing a little research, I found some symphony PDF creation packages from https://www.getparthenon.com that were easy to install on my side. Now my visitors can get reports in a PDF file and download them as they see fit.