Simple EventAggregator

Once again I’m missing a clear event management system in the unity framework. There is an event system integrated for broadcast and hierarchical events, and the .net framework covers the usual events you can hook on, but what i really needed was an event-bus implementation.

Sime kind instance of an eventmanager, where you can subscribe to specific events and publish them with an easy way to define new events. In may daily serious work-life we are using the prism framework for some of our tools, where an eventbus implementation is included. I therefore created a very simple clone of the eventbus and eventbase, which allows to register for events. Integrating this in unity3d was quite straight forward.

Let’s start with the eventbase class, which is really quite simple:

With this set up an event can be defined as follow:

On to the eventaggregator, which is not more complex either

I’ve implemented it due to simplicity as a static class. You could work with the singleton pattern, which is of course not the ideal solution. It would be better to have a service locator or work with dependency injection.

And that’s essentially it. Not that much code though.

Now let’s put it all together and show to actually use it:

A last note – since events do not get unregistered automatically (this is a strong reference, that garbage collector will let the objects stay alive), it is important where to subscribe/unsubscribe.

For me it worked well to be registered during the time the element is enabled and active in unity. This means registering in the OnEnable() method and unsubscribing in the OnDisable() method (also gets called before the object is destroyed).

Hope this can help someone ;)

Leave a Reply

Your email address will not be published. Required fields are marked *