Skip to content

Instantly share code, notes, and snippets.

@takumifukasawa
Created January 21, 2023 06:53
Show Gist options
  • Save takumifukasawa/bb5017b05f2b9ae73f41d69776d5cef9 to your computer and use it in GitHub Desktop.
Save takumifukasawa/bb5017b05f2b9ae73f41d69776d5cef9 to your computer and use it in GitHub Desktop.
unity simple service locator with singleton component
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