Manual

Manual

A game's start, flows and services

Not all of a game's code is systems. Some of it has to wait, such as a wave of enemies one after another, a download or signing in, and some of it happens once, as the game starts or stops. This page covers the order a game starts and stops in, the hooks a plugin has for each step, flows, async code on the engine thread, and the services a game keeps beside the world. Code that is not a system introduces them.

How a game starts and stops

A game on its own

  1. The engine registers every component the game and its packages declare, opens the window and reads the project's settings.
  2. It builds the plugins: each package's, after the packages it needs, then the game's own. See The order systems run in.
  3. It calls each plugin's BeforeFirstScene, one after another in the order they were built, waiting for each to finish before the next. The window shows an empty world meanwhile.
  4. It opens the first scene: the first one ticked in File ▸ Build Settings..., unless a plugin chose another.
  5. Once that scene is shown, or has failed to load, it calls each plugin's Started, then starts the flows, in the order they were added.
  6. Each frame, before the frame's systems run, the code waiting in an await whose wait is over goes on.
  7. When the game is asked to end, by world.Application.Quit(), the window's close button or Alt+F4, it finishes the frame, calls each plugin's Stopping with the world still there, ends its async code, and closes.

In the editor

Play loads the game's C# afresh and does steps 2 to 6 with the scene open in the editor: BeforeFirstScene runs, but the scene that plays is the open one, so what it sets as the first scene is passed over. Stop, world.Application.Quit() from the game's code, or the scripts being built again while it plays, do step 7: Stopping, the async code ended, then the services the game added since Play disposed and the world put back as it was at Play.

Plugins marked [ExecuteAlways] or [EditorOnly] run while the game is edited, so they start as the editor opens the game, and again each time it loads the game's scripts, which every Play does; they are stopped before each new load. GameStart.InEditor is true for every plugin the editor starts, and world.GameMode says whether the game is being edited, playing or paused.

In a browser

A game in a browser runs until its page is closed. world.Application.Quit() ends nothing a player sees there (world.Application.CanQuit is false), and nothing of the game runs as the page closes, so Stopping is not called. Save what the player changes when it changes, rather than only as the game stops.

A plugin's hooks

IPlugin has three hooks besides Build. Each is optional: a plugin that does not write one costs nothing for it. Each runs between frames on the engine thread, where the world is the code's own, never in the middle of the systems.

using System.Net.Http;using Abyss.Core;using MyGame;
[assembly: AbyssPlugin<Online>]
namespace MyGame;
public sealed class Online : IPlugin{    public void Build(Schedule schedule)    {        schedule.World.Services.Add(new HttpClient());    }
    // Before any scene is read: the first scene waits until this is over.    public async Task BeforeFirstScene(GameStart start)    {        HttpClient http = start.World.Services.Get<HttpClient>();        string level = await http.GetStringAsync("https://example.com/todays-level", start.Stopping);        start.FirstScene = SceneAddress.FromId(AssetGuid.Parse(level));    }
    // The first scene is there.    public void Started(World world) => Log.Info("The first scene is open.");
    // Stop, quitting, the scripts built again: save and sign out here.    public void Stopping(World world) => Log.Info("Stopping.");}
HookWhen it runsWhat it is for
Task BeforeFirstScene(GameStart start)Before the first scene is read, each plugin's in turn, each awaited before the next.Reading a save, signing in, fetching what the game is set up with, choosing the first scene. It may await.
void Started(World world)Once the first scene is shown, before the flows start.What needs the first scene's entities.
void Stopping(World world)As the game stops, before its async code is ended, with the world as the game left it.Saving, signing out, closing what the game opened. It cannot await.

GameStart gives the hook what a flow has (see Flows): the world, the Stopping token, assets, scenes, packs and the waits. Its FirstScene is the scene the game opens, by its key: Addresses.Scenes.Title, or a key made from an identity kept in a save, SceneAddress.FromId(id). Null opens no scene. A later plugin's choice replaces an earlier one's.

A hook that throws is written to the Logs panel, Online could not start: ... or could not stop, and the next plugin's hook runs all the same.

Flows

A flow is an async method that goes on over frames, added in Build. It starts once the game has started, after every plugin's Started, and is ended with the game. A flow added after that, from a hook, starts at once.

schedule.AddFlow("Waves", static async flow =>{    PrefabId enemy = flow.Assets.LoadPrefab(Addresses.Enemy);    if (await flow.Loaded(enemy) != AssetState.Loaded)    {        return;    }
    for (int wave = 0; wave < 10; wave++)    {        flow.World.Instantiate(enemy, new Vector3(wave * 2f, 0f, 0f), Quaternion.Identity);        await flow.Seconds(2f);    }});

A flow has World, Stopping, Assets, Scenes, Packs and its Name, and waits with these:

WaitComes back
NextFrame()At the next frame, before its systems run.
Seconds(seconds)After that many seconds of the game's time, which stands still while it is paused and follows the time scale.
Until(() => ...)Once the function says true, asked once a frame.
Loaded(id)Once a prefab, mesh, material, image or sound clip has loaded or failed, saying which (AssetState); for a scene, Active, Ready for one held, or None for one that failed (SceneState).
Unloaded(scene)Once the scene is gone.
AnimationEvent<T>(animator)With the next event of type T a clip fires on the animator.
Play(animator, clip)Once the clip has played to its end (true), or was stopped, replaced or refused (false).
Ended(action)Once an action that world.Play gave has ended.
Rebind(input, action)With what the player pressed for an action, or null where they canceled; see Rebinding.
Prepare(...)Once what the game will draw has been drawn once out of sight and is ready, so it holds no frame up later.

Between waits a flow changes the world directly: flow.World.Instantiate, flow.Scenes.Load, flow.World.SetLayer, or a command buffer of its own from flow.World.CreateCommandBuffer(), applied with flow.World.Apply. What a flow throws is written to the Logs panel as the flow Waves failed: ...; one that ends because the game stopped says nothing.

Async code on the engine thread

Whatever a hook or a flow awaits, the code after the await runs on the engine thread, once a frame before the systems. The work itself, such as a web request, goes on wherever .NET runs it; only what follows comes back, and it may spawn, load and write as freely as the code before the await.

  • flow.Seconds waits the game's time. await Task.Delay(...) waits real time, and goes on while the game is paused.
  • await Task.Run(...) runs work on another thread and comes back with the result.
  • ConfigureAwait(false) tells .NET not to come back to the engine thread, so code after it must not touch the world. Leave it out of game code.
  • It stops with the game. The Stopping token, the same as start.Stopping, flow.Stopping and schedule.Stopping, is canceled as the game stops, and nothing the game's code was waiting for comes back after that: no line of a stopped game runs against a world that has been put back. Pass the token to what takes one, as HttpClient does, so the work itself stops too.
  • What an async void method throws after an await is written to the Logs panel. A Task started and never awaited that fails says nothing, so await what you start.

A system cannot wait

A system's context exists only while the system runs, so a system cannot start async code. When a system sees something that needs time, it records it in a resource, and a flow waits for that:

ResourceType<Doorbell> bell = world.RegisterResource<Doorbell>();world.InsertResource(bell);
// The system notices.schedule.Add("Ring", [visitor.Read()], default, [bell.Write()], static context =>{    if (context.Chunks.EntityCount > 0)    {        context.ResourceMut<Doorbell>(0).Value.Rung = true;    }});
// The flow acts, over as many frames as it takes.schedule.AddFlow("Answer", async flow =>{    World world = flow.World;    while (true)    {        await flow.Until(() => world.ResourceValue(bell).Rung);        world.ResourceValue(bell).Rung = false;        await flow.Seconds(1.5f);        Log.Info("Coming!");    }});

Between frames, world.ResourceValue(resource) reads and writes a resource in place, and world.Settings<T>() a project's settings.

Services

world.Services holds objects a game keeps that are not ECS data, such as an HttpClient, a connection or a store's SDK: one of each type, found by the type.

CallWhat it does
Add(service)Adds it, found by its type from then on. Throws if there is one of that type already.
Get<T>()The service of type T; throws if there is none.
TryGet<T>(out T? service)The same, false where there is none.
Remove<T>()Takes it away; disposing it is up to you.

A plugin adds what it makes in Build, and other code finds it: another plugin, a hook through start.World.Services or its world, a flow through flow.World.Services, and a system through context.Services. Packages give theirs the same way: Physics 2D is context.Services.Get<Physics2D>(). Adding and finding are safe from any thread, and a service used from several threads at once must be safe for that itself, as HttpClient is. A parallel system's slices cannot reach services; get what the slices need before the loop.

In the editor, Stop takes away what the game added since Play, the last first, disposing each one that is IDisposable, so the next Play adds them afresh.

In the Scripting API

  • IPlugin: Build and the three hooks.
  • GameStart: what BeforeFirstScene is given, and the first scene.
  • Flow and GameCode: code that waits across frames, and what it can wait for.
  • Services: the objects a game keeps beside the world.
  • GameApplication: Quit, and whether the game plays in the editor or a browser.
  • GameMode: whether the game is being edited, playing or paused.