Skip to content

Instantly share code, notes, and snippets.

@ZacharyBuffone
Last active March 9, 2022 14:22
Show Gist options
  • Save ZacharyBuffone/df9d2fb0ab1a2032c9b205aa31eda10c to your computer and use it in GitHub Desktop.
Save ZacharyBuffone/df9d2fb0ab1a2032c9b205aa31eda10c to your computer and use it in GitHub Desktop.
PubSub For Unity Scripting
//MIT LICENCE
//Copyright 2022 Zachary Buffone
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static class PubSub {
private static Dictionary<string, List<Tuple<PubSubID, Action<object>>>> dict = new Dictionary<string, List<Tuple<PubSubID, Action<object>>>>();
public static void Initialize() {
UnityEngine.SceneManagement.SceneManager.sceneUnloaded += (_) => {
dict.Clear();
};
}
public static PubSubID Subscribe(string action, Action<object> callback) {
if(!dict.ContainsKey(action)) {
dict.Add(action, new List<Tuple<PubSubID, Action<object>>>());
}
var id = new PubSubID();
dict[action].Add(new Tuple<PubSubID, Action<object>>(id, callback));
return id;
}
public static void Publish(string action, object payload) {
#if DEVELOPMENT_BUILD
if(!dict.ContainsKey(action)) {
Debug.LogWarning("Trying to publish to nonexistant action " + action);
return;
}
#endif
foreach(var a in dict[action]) {
a.Item2.Invoke(payload);
}
}
public static void Unsubscribe(string action, PubSubID id) {
if(!dict.ContainsKey(action))
throw new System.Exception("Trying to unsubscribe from nonexistant action " + action);
var index = dict[action].FindIndex(t => t.Item1 == id);
if(index == -1)
throw new System.Exception("Could not find matching PubSubID in action " + action);
dict[action].RemoveAt(index);
}
}
public class PubSubID : IComparable {
private static ulong ID_COUNT;
private ulong id;
public PubSubID() {
this.id = ID_COUNT++;
}
public int CompareTo(object obj)
{
if(obj is PubSubID psid) {
return (int)psid.id - (int)this.id;
} else {
throw new ArgumentException("Argument must be of type PubSubID");
}
}
public static bool operator==(PubSubID left, PubSubID right) {
return left.id == right.id;
}
public static bool operator!=(PubSubID left, PubSubID right) {
return left.id != right.id;
}
public override bool Equals(object obj) {
if(obj is PubSubID psid) {
return psid.id == this.id;
} else {
throw new ArgumentException("Argument must be of type PubSubID");
}
}
public override int GetHashCode() {
return (int)this.id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment