An event class that has extra checks to help prevent mistakes.
It will notify you when you've subscribed more than once with the same callback. In case your callback lies within a MonoBehaviour it will also detect if that behaviour and/or the GameObject has been destroyed and will let you know if you forgot to unsubscribe from the event.
- The package is available on the openupm registry. You can install it via openupm-cli.
openupm add net.tnrd.safeevent
- Installing through a Unity Package created by the Package Installer Creator from Needle
There are three versions of Safe Event that you can use. One without any parameters, one with a single parameter, and one with two parameters.
The definition is the same as you would define an Action
private SafeEvent onFooEvent;
private SafeEvent<int> onFooEvent;
private SafeEvent<int, string> onFooEvent;
Subscribing and unsubscribing can be done in two ways.
One way is through the Subscribe and Unsubscribe methods
private void SubscribeToEvent()
{
onFooEvent.Subscribe(ExecuteOnEvent);
}
private void ExecuteOnEvent()
{
[...]
}
private void UnsubscribeFromEvent()
{
onFooEvent.Unsubscribe(ExecuteOnEvent);
}
And the other is through the use of operators
private void SubscribeToEvent()
{
onFooEvent += ExecuteOnEvent;
}
private void ExecuteOnEvent()
{
[...]
}
private void UnsubscribeFromEvent()
{
onFooEvent -= ExecuteOnEvent;
}
Invoking the event is the same as you would invoke a regular event
private SafeEvent onFooEvent;
[...]
private void InvokeEvent()
{
onFooEvent.Invoke();
}
private SafeEvent<int> onFooEvent;
[...]
private void InvokeEvent()
{
onFooEvent.Invoke(123);
}
private SafeEvent<int, string> onFooEvent;
[...]
private void InvokeEvent()
{
onFooEvent.Invoke(123, "abcde");
}
Now that you've set up your Safe Event you most likely want to be able to use it from a different place.
The recommended way of doing this is by exposing an event property as shown below, instead of directly exposing the Safe Event
private SafeEvent<int> onFooEvent;
public event Action<int> OnFooEvent
{
add => onFooEvent.Subscribe(value);
remove => onFooEvent.Unsubscribe(value);
}
The benefit of this is that to the outside it looks and behaves like a normal event even though under the hood it has the benefits of the Safe Event.
Safe Event is a small and open-source utility that I hope helps other people. It is by no means necessary but if you feel generous you can support me by donating.
Pull requests are welcomed. Please feel free to fix any issues you find, or add new features.