DCS/ruiyiweiUX/Assets/Scripts/Services/ServiceLocator.cs

47 lines
902 B
C#
Raw Normal View History

2026-06-09 13:59:11 +08:00
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));
}
}