Services

It is sometimes suitable to have a class that can be accessed from all your actors and components. This is can be done with Services which are classes that can be injected in your actors and components. There will only be one instance of the service. This is similar to the Singleton design pattern. It can serve many purposes:

  1. Global access: Services provide a convenient way to access a specific object or functionality from anywhere in your game's codebase. This can be helpful for managing and sharing resources, game state, or services such as audio managers, input handlers, or configuration settings.

  2. Game state management: Services can be used to manage the overall state of the game, including aspects like score, level progression, or the current game mode. This helps in maintaining a consistent game state across various parts of the code.

  3. Configuration settings: Storing and accessing global configuration settings or variables is a common use case.

  4. Cross-actor communication: Services can facilitate communication between different actors or systems by providing a shared interface. For example, event emitters can be placed on a service to inform every actor throughout your game when an event occurs.

Creating services

To create a service, all you need to do is to add the @Service() decorator on your class.

// src/services/game-state.ts
import { Service } from "@hology/core/gameplay";

@Service()
class GameState {
  score: number
}

export default GameState

Injecting services

A service can be used from any actor or component by using the inject function and pass in the service's class.

// src/actors/goal.ts
import { Actor, BaseActor, inject, } from "@hology/core/gameplay";
import Service from "../services/game-state.ts"

@Actor()
class Goal extends BaseActor {
  private gameState = inject(GameState)
}

Built in services

Here are some services that may be useful to you that also provide example use cases for services.

  • World: The world service can be used to spawn actors.

  • PhysicsSystem: Manages all physics in your game. Can be used to setup physics for an actor, apply forces to actors, and subscribe to collision events.

  • ViewController: An interface towards the engine's rendering. Can be used for setting the active camera or pausing/resuming rendering.

Last updated