Last active
October 25, 2024 21:38
-
-
Save j4rv/c0bce66f9a16356f99ca431a6c1bf348 to your computer and use it in GitHub Desktop.
Unity Service Locator Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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