Non-thread-safe event manager. Use only in single thread environment. Preferably Unity thread.
GPL-3.0 License
This library is distributed via Unity's built-in package manager. Required Unity 2018.3 or later. Sinse Unity's package manager does not support git-url dependencies you should install them manually, if required.
# go to the unity project folder
$ cd ~/Document/projects/hello-openupm
# add package
$ openupm add com.vadimskyi.eventmanager
Define the class for your event and derive it from EventBase<ClassName>
abstarct base class.
public class TestEvent : EventBase<TestEvent>
{
}
Optionally, you can also define argument data or pass it directly for the generic argument type.
public class PlayerMovedEvent : EventBase<PlayerMovedEvent, PlayerMovedData>
{
}
public readonly struct PlayerMovedData
{
public readonly int PlayerId;
public readonly Vector3 Position;
public PlayerMovedData(int id, Vector3 pos)
{
PlayerId = id;
Position = pos;
}
}
Subscribe to event:
public class SomeEventListener : MonoBehaviour
{
public void Start()
{
PlayerMovedEvent.Subscribe(OnPlayerMoved);
}
public void OnPlayerMoved(PlayerMovedData data) { ... }
public void OnDestroyed()
{
PlayerMovedEvent.Unsubscribe(OnPlayerMoved);
}
}
Invoke event:
public class Player : MonoBehaviour
{
private int _playerId;
public void Update()
{
if(positionChanged)
{
PlayerMovedEvent.Invoke(new PlayerMovedData(_playerId, transform.localPosition));
}
}
}
Internally, this event manager is operating as "global" manager. Meaning that every event subscription will be persistent through all application lifecycle, unless unsubscribed manually. This, in fact, makes unsubscription of anonymous delegates problematic. More on this issue: https://stackoverflow.com/questions/25563518/why-cant-i-unsubscribe-from-an-event-using-a-lambda-expression/25564492#25564492 Bottom line is: try not to use anonymous delegates with this [Event Manager] if possible.
Vadim Zakrzhewskyi (a.k.a. Vadimskyi) a software developer from Ukraine.
~10 years of experience working with Unity3d, mostly freelance/outsource.