Skip to content

Instantly share code, notes, and snippets.

@Wolfos
Last active May 24, 2023 09:19
Show Gist options
  • Save Wolfos/fc0b1a03d4036b3cbaa1cbdf3a09e952 to your computer and use it in GitHub Desktop.
Save Wolfos/fc0b1a03d4036b3cbaa1cbdf3a09e952 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
public static class ServiceRegistry
{
// This is a Dictionary (a type of list) of all objects currently registered, by their type
private static Dictionary<System.Type, object> _services = new();
// Usage: ServiceRegistry.Register(this)
// Please only register one instance of each type
public static void Register(object obj)
{
_services.Add(obj.GetType(), obj);
}
public static void UnRegister(object obj)
{
_services.Remove(obj.GetType());
}
// Usage: Foo foo = ServiceRegistry.Get<Foo>();
public static T Get<T>()
{
object system;
// Try to get a system out of our Dictionary
_services.TryGetValue(typeof(T), out system);
// If it fails, throw an error. No class of that type was registered
if (system == null) Debug.LogError("Could not find system of type " + typeof(T));
// Return the system (can be null)
return (T)system;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment