47 lines
902 B
C#
47 lines
902 B
C#
|
|
using System;
|
||
|
|
using System.Collections.Generic;
|
||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
public interface IService { }
|
||
|
|
|
||
|
|
public static class ServiceLocator
|
||
|
|
{
|
||
|
|
private static readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
|
||
|
|
|
||
|
|
public static void Register<T>(T instance) where T : class
|
||
|
|
{
|
||
|
|
var type = typeof(T);
|
||
|
|
if (instance == null)
|
||
|
|
{
|
||
|
|
Debug.LogError($"Attempt to register null service: {type.Name}");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
if (_services.ContainsKey(type))
|
||
|
|
{
|
||
|
|
_services[type] = instance;
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
_services.Add(type, instance);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public static T Get<T>() where T : class
|
||
|
|
{
|
||
|
|
object service;
|
||
|
|
if (_services.TryGetValue(typeof(T), out service))
|
||
|
|
{
|
||
|
|
return service as T;
|
||
|
|
}
|
||
|
|
Debug.LogError($"Service of type {typeof(T).Name} not registered.");
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static bool IsRegistered<T>() where T : class
|
||
|
|
{
|
||
|
|
return _services.ContainsKey(typeof(T));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
|