01. Hello, World!

  03. Getting Started No Comments

Service Injection 101

Here is a quick showcase of how a service can be injected to a component:

ExampleService.cs:

using Sisus.Init;
using UnityEngine;

[Service]
class ExampleService
{
    public void Hello() => Debug.Log("Hello, World!");
}

ExampleComponent.cs:

using Sisus.Init;
using UnityEngine;

class ExampleComponent : MonoBehaviour<ExampleService>
{
    protected override void Init(ExampleService service) => service.Hello();
}
  1. Create script files from the two snippets of code above.
  2. Attach the ExampleComponent component to a GameObject in a scene
  3. Enter Play Mode.

You should see “Hello, World!” printed in the Console window.

How It Works

When the game is launching, Init(args) finds all types in the project that have the [Service] attribute, and creates and caches a single instance out of each one. This takes places just before the first scene is loaded.

When a component that derives from a MonoBehaviour<T…> class is being loaded, and all generic arguments of its base class are service types, then the component will automatically receive instances of those services in its Init function.

Since ExampleService has the [Service] attribute, and single instance of it is created right before the first scene is loaded, and because ExampleComponent derives from MonoBehaviour<T…>, it automatically receives a reference to the service when it is being loaded.

Usually a component would use the Init function just to assign all the received objects into member variables, and then all the actual work where those services are used would take place in other methods, such as Start or Update. However for the sake of brevity in the above example the ExampleComponent just immediately invokes the Hello method in the service object, causing the “Hello, World!” text to get printed.

Note: if not all Init arguments of a component are services, then an Initializer can be used to specify the rest of the injected arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *