Last active
May 24, 2023 09:19
-
-
Save Wolfos/fc0b1a03d4036b3cbaa1cbdf3a09e952 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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