Adding a generic solution
Our generic service locator is going to have the exact same features as the static locator we already built, but instead of knowing what services it’s managing beforehand, we’ll register services dynamically. Not only is this more flexible, but it also allows us to register and unregister services while our game is running!
In the Scripts folder, create a new C# script named GenericLocator
and update its contents to match the following code block:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 1
using System;
// 2
public class GenericLocator
{
// 3
private static readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
// 4
public static int Services
{
get { return _services.Count; }
}
}
Let’s break down the first portion of our generic locator solution:
- Declares the new Service Locator class
- Adds a private...