일단은 서비스 딕셔너리를 생성해준 후 indexer로 Type 값을 반환한다
여기서 instance는 싱글톤 객체를 의미한다
private Dictionary<Type, object> _services = new Dictionary<Type, object>();
public object this[Type type]
{
get
{
if (_services.TryGetValue(type, out object service))
return service;
Debug.LogWarning($"Service of type {type.Name} not found!");
return null;
}
set
{
if (_services.ContainsKey(type))
{
Debug.LogWarning($"Service of type {type.Name} already registered. Overwriting...");
_services[type] = value;
}
else
{
_services.Add(type, value);
Debug.Log($"Service of type {type.Name} registered successfully.");
}
}
}
자주 쓰여지는 것들은 아래 함수들을 활용하면 된다
public static object GetInstance(Type type) =>instance[type];
public static T GetInstance<T>() where T : class => HasInstance<T>() ? instance.Get<T>() : null;
public static void RegisterInstance<T>(T service) where T : class => instance.Register(service);
public static void UnregisterInstance<T>() where T : class => instance.Unregister<T>();
public static bool HasInstance<T>() where T : class => instance.HasService<T>();
이렇게 활용하면 된다
ServiceLocatorManager.GetInstance<PlayerController>();
자주 안쓰여지는것들은 instance. 해도 무방하다
public void Register<T>(T service) where T : class
{
Type type = typeof(T);
this[type] = service;
}
public T Get<T>() where T : class
{
Type type = typeof(T);
object service = this[type];
return service as T;
}
public void Unregister<T>() where T : class
{
Type type = typeof(T);
if (_services.ContainsKey(type))
{
_services.Remove(type);
Debug.Log($"Service of type {type.Name} unregistered.");
}
}
public bool HasService<T>() where T : class => _services.ContainsKey(typeof(T));
public void ClearAll()
{
_services.Clear();
Debug.Log("All services cleared.");
}'게임엔진 > Unity' 카테고리의 다른 글
| [Unity] 커스텀 셰이더 UnityCG.cginc 헤더 파일 못찾는 이유 (0) | 2025.12.27 |
|---|---|
| [Unity] fps 로그창 GUI (0) | 2025.12.13 |
| [Unity] 애니메이션 마지막 프레임에서 이벤트 호출안되는 이유 (0) | 2025.11.23 |
| [Unity] 로그 (Log) 출력시 스택 트레이스 (Stack Trace) 관리하기 (0) | 2025.10.07 |
| [Unity] PlayerInput을 활용한 캐릭터 움직이는 방법 (0) | 2025.08.04 |