Skip to content

07 ‐ Using Lifecycle Hooks in Services

Marco Klein edited this page Aug 23, 2024 · 1 revision

Use

Sometimes, you do not want a node just for attaching to some events of the Game Rendering Lifecycle. Godough provides you with interfaces declaring a certain hook. You can compose multiple by implementing all hooks that you require within your service.

For example, you could use the IOnProcess interface for implementing a service that tracks the ticks run past since the start of the game:

using GoDough.Runtime.LivecycleHooks;

// Registration withing AppHost.ConfigureServices
services
  .AddSingleton<GameTimeService>()
  .MapSingleton<IOnProcess, GameTimeService>()

// Implement OnProcess Event for a GameTimeService
public class GameTimeService : IOnProcess {
	public float CurrentTicks { get; private set; } = 0;

	public void OnProcess(double delta) {
		this.CurrentTicks += (float)delta;
  }
}

OnInput

using GoDough.Runtime.LivecycleHooks;

// Registration withing AppHost.ConfigureServices
services
  .AddSingleton<GameTimeService>()
  .MapSingleton<IOnInput, GameTimeService>()

// Implement Event for a GameTimeService
public class MyService : IOnInput {
	public float CurrentTicks { get; private set; } = 0;

	public void OnInput(InputEvent ev) {
		// Do something...
  }
}

OnProcess

using GoDough.Runtime.LivecycleHooks;

// Registration withing AppHost.ConfigureServices
services
  .AddSingleton<GameTimeService>()
  .MapSingleton<IOnProcess, GameTimeService>()

// Implement OnProcess Event for a GameTimeService
public class GameTimeService : IOnProcess {
	public float CurrentTicks { get; private set; } = 0;

	public void OnProcess(double delta) {
		this.CurrentTicks += (float)delta;
  }
}

OnPhysicsProcess

using GoDough.Runtime.LivecycleHooks;

// Registration withing AppHost.ConfigureServices
services
  .AddSingleton<GameTimeService>()
  .MapSingleton<IOnPhysicsProcess, GameTimeService>()

// Implement Event for a GameTimeService
public class MyService : IOnPhysicsProcess {
	public float CurrentTicks { get; private set; } = 0;

	public void OnPhysicsProcess(double delta) {
		// Do something...
  }
}

OnUnhandledInput

using GoDough.Runtime.LivecycleHooks;

// Registration withing AppHost.ConfigureServices
services
  .AddSingleton<GameTimeService>()
  .MapSingleton<IOnUnhandledInput, GameTimeService>()

// Implement Event for a GameTimeService
public class MyService : IOnUnhandledInput {
	public float CurrentTicks { get; private set; } = 0;

	public void OnUnhandledInput(InputEvent ev) {
		// Do something...
  }
}