A super simple, lightweight, and fast PubSub pattern for Unity.
Window > Package Manager > (+) Plus Button > Add Package form git Url
git URL:
https://github.com/stupeak/SimplestPubSubEver.git?path=Assets/SimplestPubSubEver
using Stupeak.SimplestPubSubEver;
struct LoadScenePayLoadMessage : IMessage
{
public float value;
}// ubsubscribe via subscription
ISubscription subscription;
void Awake()
{
Subscriber subscriber = Messenger.MessageSubscriber();
// or
//Subscriber subscriber = new();
// subscribe
subscriber.Subscribe<LoadScenePayLoadMessage>(static (payload) =>
{
UnityEngine.Debug.Log($"value: {payload.value}");
});
}
void Destroy()
{
subscription?.Dispose();
}void Start()
{
//create a message and publish to subscribers who are already subscribed to this event.
LoadScenePayLoadMessage payload = new LoadScenePayLoadMessage(999, "Success");
Publisher publisher = Messenger.MessagePublisher();
publisher.Publish(payload);
}subscriber.Subscribe<InfoMessage>(OnNotify);
void OnNotify() // message param is unnecessary
{
}subscriber.Subscribe<Message>(() => { Debug.Log("hello world"); }, Channel.FromType<Message>()));
publisher.Publish(new Message(), Channel.FromType<Message>());SubscriptionBag is a list of ISubscription, allowing you to unsubscribe multiple subscriptions at once.
SubscriptionBag subscriptions = new(4);
subscriber.Subscribe<M1>(() => { }).AddTo(subscriptions);
subscriber.Subscribe<M1>((m) => { }).AddTo(subscriptions);
subscriber.Subscribe<M2>((m) => { }).AddTo(subscriptions);
subscriptions?.Dispose();