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.