Created
January 21, 2023 06:53
-
-
Save takumifukasawa/bb5017b05f2b9ae73f41d69776d5cef9 to your computer and use it in GitHub Desktop.
unity simple service locator with singleton component
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; | |
using System.Collections.Generic; | |
namespace Utilities | |
{ | |
// singleton: https://gist.github.com/takumifukasawa/9519ed0f64abdf68608d098a3441b0d9 | |
public class ServiceLocator : SingletonComponent<ServiceLocator> | |
{ | |
private static Dictionary<Type, object> _dictionary = new Dictionary<Type, object>(); | |
void Awake() | |
{ | |
base.Awake(); | |
} | |
public void Register<T>(object obj) | |
{ | |
if (!_dictionary.ContainsKey(typeof(T))) | |
{ | |
_dictionary.Add(typeof(T), obj); | |
} | |
} | |
public T Resolve<T>() where T : class | |
{ | |
if (_dictionary.ContainsKey(typeof(T))) | |
{ | |
return _dictionary[typeof(T)] as T; | |
} | |
return default(T); | |
} | |
public void Clear() | |
{ | |
_dictionary = new Dictionary<Type, object>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment