Skip to content

Instantly share code, notes, and snippets.

@DevEarley
Last active October 10, 2022 20:13
Show Gist options
  • Save DevEarley/7eeb7090429fd6f59203e5153593b92f to your computer and use it in GitHub Desktop.
Save DevEarley/7eeb7090429fd6f59203e5153593b92f to your computer and use it in GitHub Desktop.
Service Locator pattern in Unity3D

Service Locator pattern in Unity3D

Using the Service Locator pattern in Unity allows you connect various services together to a single source. When a script needs access to something on the Service Locator, it just needs to access the Service Locators's Instance. This instance will have any service the invoker may need.

To setup, the service must be referenced in the script and the script must find these services on Awake. You can look them up by the GameObject they are attached to or attach them to the Service Locator's GO. In this example, I use GetComponentInChildren<T>(). Alternatively you can search for the GameObject by name and then get the component, PlayerController = GameObject.Find("PlayerController").GetComponent<PlayerController>();

  • Contains references to all Controllers and all Services.
  • Attached to a GO.
  • Must reference all controllers and services automatically.
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour
{
void Start()
{
ServiceLocator.Instance.UIController.ShowIntroText();
}
}
using UnityEngine;
using System.Collections;
public class ServiceLocator : MonoBehaviour
{
public static Singleton Instance { get; private set; }
public UIController UIController { get; private set; }
public PlayerController PlayerController { get; private set; }
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
return;
}
Instance = this;
UIController = GetComponentInChildren<UIController>();
PlayerController = GameObject.Find("PlayerController").GetComponent<PlayerController>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment