Skip to content

Instantly share code, notes, and snippets.

@Novack
Forked from j4rv/ServiceLocator.cs
Created October 25, 2024 21:38
Show Gist options
  • Save Novack/2a5c32820939784698c0afc8c86417c0 to your computer and use it in GitHub Desktop.
Save Novack/2a5c32820939784698c0afc8c86417c0 to your computer and use it in GitHub Desktop.
Unity Service Locator Component
using System.Collections.Generic;
using UnityEngine;
public class ServiceLocator : MonoBehaviour {
private Dictionary<System.Type,Object> cache = new Dictionary<System.Type,Object>();
private static ServiceLocator _singleton;
private static ServiceLocator singleton {
get {
if(!_singleton){
GameObject go = new GameObject();
go.name = "ServiceLocator";
_singleton = go.AddComponent<ServiceLocator>();
}
return _singleton;
}
}
/**
* Add Services as public static Get methods.
* Example:
* public static ChatManager GetChatManager(){
* return GetService<ChatManager>("ChatManager");
* }
*/
private static T GetService<T>() where T : Object {
Object cached;
System.Type key = typeof(T);
singleton.cache.TryGetValue(key, out cached);
if(!cached){
cached = GameObject.FindObjectOfType<T>();
if(!cached){
Debug.LogError("Could not find the Service :" + key.Name);
return null;
} else {
Debug.Log("Caching Service: " + key.Name);
singleton.cache.Add(key, cached);
}
}
return cached as T;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment