Service Locator

The ServiceLocator class provides a way to manage services in your Unity project. It handles the registration, retrieval, and removal of services, supporting both MonoBehaviour and non-MonoBehaviour types. This pattern is useful for dependency management, allowing services to be loosely coupled while remaining accessible throughout the project.

Usage

Register

ServiceLocator.Register(new ServiceDescriptor(myInstance));

Register with custom Type

ServiceLocator.Register(new ServiceDescriptor(typeof(IMyService), myInstance));

Retrieve

IMyService myInstance = ServiceLocator.Get<IMyService>();

Retrieve Silent

Returns null instead of throwing an error.

IMyService myInstance = ServiceLocator.Get<IMyService>(silent: true);

Remove

ServiceLocator.Remove(myInstance);

ServiceLocatorRegisterMono

Register/Unregister services on Awake/OnDestroy.

using UnityEngine;
using CupkekGames.Core;

public class ExampleSL : ServiceLocatorRegisterMono
{
  [SerializeField] private MyCustomClass myGameObject;

  public override void RegisterServices()
  {
    ServiceLocator.Register(new ServiceDescriptor(myGameObject));
  }

  public override void UnregisterServices()
  {
    ServiceLocator.Remove(myGameObject);
  }
}

Last updated