Using Native C# Events in Unity

EventSystem_Native

Github: https://github.com/rakibj/Unity-Helper/tree/master/Assets/_UnityHelper/EventSystem_Native

It contains a framework to use C# event system (not UnityEvents). C# event system is more optimized in most cases than Unity Event System. Unless you want to drag and drop references in Unity Editor as a listeners, this is the better way to implement Events

GameEvents.cs

This is the class where events are declared. It is a static class so it doesn’t have to be attached with a Gameobject and it doesn’t inherit Monobehaviour. It can persist among scenes. It’s content will be different based on project

There are 3 steps to this

  1. Declare an event
  2. Invoke it from somewhere
  3. Add listener for this event

1. Declare an event

A simple event declaration looks like this

public static event Action NoArgumentEvent;

As this is a delegate we can’t invoke it from outside this class. To resolve this we create a static function that will Invoke this event and we will call this new method from outside class to invoke the event. The function looks like this

public static void OnNoArgumentEvent() 
{ 
  NoArgumentEvent?.Invoke(); 
}

2. Invoke it from somewhere

We invoke this event from anywhere using

GameEvents.OnNoArgumentEvent();

3. Add listener for this event

We add listener for this event on as many classes as we want. This essentially creates response of different scripts due to something happening

First, We create a function with the response on any class we want. The signature of the event must match with the response function. As this event doesn’t have any parameter, the response function won’t have any

private void OnNoArgumentEventListener()
{

Debug.Log("NoArgument Event Received from class " + this.name + " . Data received: No data");

}

Last thing to do is Register this function to the event on Enable and Unregister on disable

Register:

GameEvents.NoArgumentEvent += OnNoArgumentEventListener;

Unregister:

GameEvents.NoArgumentEvent -= OnNoArgumentEventListener;

Don’t forget to Unregister to avoid memory leaks

More

In the GameEvents.cs script there are examples on how to create Events with parameters. The main process is same with minor alterations.

Information

C# events beat UnityEvent for each number of arguments. The gap widens as more args are dispatched to the listeners. In the best case, UnityEvent takes 2.25x longer than C# events but in the worst case it takes almost 40x longer!

In conclusion, UnityEvent creates less garbage than C# events if you add more than two listeners to it, but creates more garbage otherwise. It creates garbage when dispatched (Update: the first time) where C# events do not. And it’s at least twice as slow as C# events. There doesn’t seem to be a compelling case to use it

Check this link for further study

Rakib Jahan
Rakib Jahan
Articles: 42