---
title: Scenes
description: Author rooted scenes and prefabs, choose a startup scene, load and
  unload levels, and manage scene ownership and multiple instances.
source_url: https://tide-engine.dev/game/scenes
source_file: docs/game/scenes.md
source_revision: d46b7bc81b49e31e268bd62d158c040ec1c9ff21
source_worktree: modified
documentation_sha256: cff5cc1f43e9cab7c438614cde0e25d6b097b0171d16e0bfbecd7198624f4f9d
documentation_scope: Website source checkout; not matched to an installed Tide
  release. Check tide version and the project toolchain.
---

<a id="scenes"></a>

# Scenes

A scene is a group of entities that load and unload together: a menu, a level, an arena. Several scenes can be loaded at once, and several copies of the same one.

```csharp
scene Arena
{
    int size = 20;
}
```

A loaded scene is an entity like any other. The declaration is its component, and its fields are the scene's state, so a system that takes `Arena` runs once per loaded arena.

<a id="systems-for-one-scene-s-entities"></a>

## Systems for one scene's entities

`with scene Arena` runs a system, a view or an event handler only for the
entities of a loaded arena; `without scene Arena`, only for the others:

```csharp
system Spinning(Spin spin, mut Transform transform, Time time, with scene Arena)
{
    transform.localRotation = Math.Mul(quaternion.Euler(0, spin.speed * time.dt, 0), transform.localRotation);
}
```

An entity is in the scene it was spawned into: the scene of the entity the code
that spawned it runs for. A loaded scene's own entity is one of its entities
too. `with Arena`, without `scene`, still takes that entity alone, as it does
for any component, so `event(Spawned) Setup(with Arena)` runs once per loaded
arena. A scene filter on its own runs for every entity of the scene.

For an empty scene, use `scene Arena;` as shorthand for `scene Arena { }`.
The same works for local scenes: `local scene Main;`. Both forms are complete
declarations, and braces remain valid.

<a id="authored-prefabs"></a>

## Authored prefabs

An authored `.tprefab` file describes a reusable rooted entity tree. The same
tree can be spawned as an entity or loaded as a scene:

```csharp
// Enemy.tprefab
prefab Enemy
{
    Transform;
    Health { value = 100 };
    Target { weapon = Weapon };
    entity Weapon
    {
        Transform { localPosition = float3(0, 1, 0) };
    }
}
```

Declare `Health` and `Target` in ordinary `.tide` code. A reference field can use
`[SceneRequired] Entity weapon;` to require a named entity in authored prefabs.
The compiler checks unused prefabs too; missing components, fields, references
and recursive inclusion are errors. Ordinary code-driven construction can still
leave these fields unset and initialize them later.

```csharp
var enemy = Spawn(Enemy, Health { value = 50 });
var level = Scene.Load(Level, LevelSettings { difficulty = 2 });
Scene.Unload(level);
```

Settings are normal root components. Component literals override only the fields
they name and can add root components. An existing component value replaces the
whole root component. A bare component argument resets that
component to its declared defaults. A match scene uses the ordinary root
`Visibility` component: `Scene.Load(Level, Visibility { group = group })`.

All entities, component values, references and parenting exist before the
instance's `Spawned` handlers run, root-first. Nested children move with their
parents and are destroyed with them. `entity Weapon : Pistol { ... }` reuses
another named prefab; fields in its block override that prefab's root. Paths such
as `Weapon.Muzzle` resolve through nested instances, and omitted values use the
authored prefab and component defaults.

Override an inherited descendant by matching its existing name with another
`entity` block. This changes values on this instance without changing Pistol:

```csharp
entity Weapon : Pistol
{
    entity Muzzle
    {
        Transform { localPosition = float3(0, 0, 0.8) };
    }
}
```

Inside an inherited descendant, only field values of existing components can
change. Match further `entity` blocks to reach deeper descendants. These blocks
cannot add, remove or replace components or children, or name another base
prefab. A nested instance's root can still add components and new named children.
Reference paths keep the scope of the prefab whose source wrote them; `this`
means the entity containing the value. Overrides do not create extra entities.

`local Spawn(Enemy)` creates local entities, and `Scene.Load` from local code
loads into the local world. References must use the corresponding `Entity` or
`LocalEntity` type. Prefab names are factories, so filters use explicit root
components. The initial limits are 1024
entities per instance and 128 nesting levels.

<a id="startup-scene"></a>

## Startup scene

An authored scene can start the game directly. In an ordinary `.tide` file, name
its declaration in project settings:

```csharp
settings
{
    startScene = Levels.Start;
}
```

`startScene` takes a prefab or scene name, including its namespace when needed,
not a string or a call. A prefab starts as a match scene with its own root,
authored values and complete tree. Normal `Spawned` handlers, systems, views,
camera and input run; no handwritten `Main` is needed. An ordinary scene can be
selected too, including a local scene for a menu outside a match.

For one run or build, override the project selection:

```sh
tide run . --scene Levels.Start --stats
tide build . --scene Levels.Start
```

This leaves project settings and any existing `Main` declaration unchanged.

<a id="main"></a>

## Main

Without a selected startup scene, the game starts in the scene called `Main`,
and there must be exactly one. It sets up the first scene, not the game loop:
the engine runs the tick.

```csharp
scene Main;

event(Spawned) Setup(with Main)
{
    Spawn(Transform { localScale = float3(1, 1, 1) }, Player);
}
```

A match `Main`, like this one, starts a single-player match with it right away. A local `Main` starts the program outside any match, usually in a menu, which starts one later (see [Local state](https://tide-engine.dev/game/local-state.md) and [Matches](https://tide-engine.dev/multiplayer/matches.md)).

<a id="loading-and-unloading"></a>

## Loading and unloading

```csharp
var arena = Scene.Load(Arena { size = 30 });
Scene.Unload(arena);
```

`Scene.Load` loads a scene into the current world and returns its entity. `Scene.Unload` unloads it, destroying every entity it owns, and so does `Destroy` on a scene's entity. `Scene.Unload` of an entity that isn't a scene does nothing. `Spawn` of a scene is an error that says to use `Scene.Load`.

Additional component arguments attach to the loaded root, for example
`Scene.Load(Arena { size = 30 }, Visibility { group = group })`. They use the
same component names, literals and existing values as `Spawn` and are present before `Spawned`
handlers run. Local scenes can also take root components, using local placement.

Loading and unloading happen at the end of the tick, like `Spawn` and `Destroy`.
A scene can do heavy preparation before its `Spawned` handlers run, as described
below. Its entities get `Destroyed` when it unloads.

<a id="switching-scenes"></a>

## Switching scenes

To leave one scene for another, switch:

```csharp
Scene.Switch(Arena { size = 30 });
```

`Scene.Switch` unloads every scene loaded in the world and loads this one,
returning its entity. It takes what `Scene.Load` takes, root components included,
and needs no handle to the scene being left, so any code can call it: a system of
the scene, or a button in a view that runs for no entity. A match scene switches
the match's scenes and a local scene this machine's. Entities in no scene stay.

It happens at the end of the tick, in its turn: scenes loaded earlier in the same
tick go too, and scenes loaded after it stay. The world is never left without a
scene, so the startup scene doesn't load in between.

Functions and methods can load, switch and unload scenes, for the code that calls
them. A function that loads a match scene is for match code to call, and one that
loads a local scene is for views and local handlers:

```csharp
local scene Menu;
local scene Lobby { int seats; }

void OpenLobby(int seats)
{
    Scene.Switch(Lobby { seats = seats });
}

view MenuButtons(with Menu)
{
    if (GUILayout.Button("Play")) OpenLobby(4);
}
```

A prefab belongs to neither side. In a function it loads into the match; write
`local Scene.Load(MenuPrefab)` or `local Scene.Switch(MenuPrefab)` to load it on
this machine instead.

<a id="from-a-menu-into-a-match"></a>

### From a menu into a match

A menu is usually a local scene, and the game a match that `Session.Start` or
`Session.Join` puts this machine in. Unload the menu as the match starts and it
stays gone for the whole match:

```csharp
local scene Main;

view Menu(with Main)
{
    if (GUILayout.Button("Play"))
    {
        Session.Start(Arena);
        Scene.Unload(this);
    }
}
```

With a local scene for the match's own interface, switch to it instead:
`Scene.Switch(Hud)`. The startup scene loads again by itself once this machine is
offline with no local scene loaded: when the match ends, the player leaves, or
joining fails. Nothing has to bring the menu back.

The startup scene is also the fallback: the selected scene or prefab, or `Main`
without a selection. When the last scene of its world unloads, the fallback loads
again at the end of that tick, initialized as at startup. A match startup returns
in the match, and a local one in local state, while this machine is offline: in a
match, or with one asked for, it waits. Unloading one scene and loading
another in the same tick never brings it back, and entities in no scene don't
count. It returns at most once a tick: one that unloads itself as it loads leaves
the world without a scene until the next.

A match can't load a local startup scene. When startup is local, a match whose
last scene unloads ends there. Every machine in it goes back offline and gets
`Disconnected` with the reason `Ended` (see [Matches](https://tide-engine.dev/multiplayer/matches.md)).
Local state carries on as it was.

```csharp
// Sets up each arena. The floor joins that arena.
event(Spawned) SetupArena(Arena arena)
{
    Spawn(Floor { size = arena.size });
}

system Collapse(Arena arena)
{
    if (arena.size <= 0) Scene.Unload(this);
}
```

Each button below loads a `Room`, or unloads the one that's there. A `Spawned` handler furnishes a room with four balls as it loads. They're spawned for the room, so they join it, and unloading it takes them with it.

**Rooms that load and unload** ([Run example](https://tide-engine.dev/examples/scenes/?stats))

```tide
settings { title = "Scenes"; tickRate = 30; maxPlayers = 1; }

scene Main { }

// A scene's fields are its state. Each loaded Room is an entity with a Room.
scene Room
{
    int slot;
}

component Ball
{
    float2 position;
    float2 velocity;
    int slot;
}

singleton Slots { List<Entity> rooms = [default, default, default]; }

float2 Center(int slot)
{
    return float2((slot - 1) * 1.3, 0);
}

command(int slot) Toggle(mut Slots slots, PlayerID sender)
{
    if (slot < 0 || slot > 2) return;
    if (slots.rooms[slot] == default)
        slots.rooms[slot] = Scene.Load(Room { slot = slot });
    else
    {
        // Unloading destroys the room and every entity spawned into it.
        Scene.Unload(slots.rooms[slot]);
        slots.rooms[slot] = default;
    }
}

// Sets each room up as it loads. These spawns join that room.
event(Spawned) Furnish(Room room)
{
    for (var i = 0; i < 4; i++)
    {
        Spawn(Ball { position = Center(room.slot), slot = room.slot,
                     velocity = float2(Math.Cos(i * 1.9 + room.slot), Math.Sin(i * 1.9 + room.slot)) * 0.9 });
    }
}

system Bounce(mut Ball ball, Time time)
{
    ball.position += ball.velocity * time.dt;
    var offset = ball.position - Center(ball.slot);
    if (Math.Abs(offset.x) > 0.4) ball.velocity.x = -Math.Sign(offset.x) * Math.Abs(ball.velocity.x);
    if (Math.Abs(offset.y) > 1) ball.velocity.y = -Math.Sign(offset.y) * Math.Abs(ball.velocity.y);
}

local singleton Count { int balls; }

view Buttons(Slots slots, mut Count count)
{
    Draw.Clear(Color(0.086, 0.086, 0.094));
    Draw.SetCamera(float2(0, 0.2), 2.2);
    count.balls = 0;
    GUI.SetTheme(GUITheme { radius = 6 });
    for (var slot = 0; slot < 3; slot++)
    {
        var loaded = slots.rooms[slot] != default;
        Draw.WireRoundRect(Center(slot), float2(1.1, 2.3), 0.1, 0.03, loaded ? Color(0.98, 0.75, 0.14) : Color(0.24, 0.25, 0.27));
        var corner = Draw.WorldToScreen(Center(slot) + float2(-0.55, -1.3));
        var width = Draw.WorldToScreen(Center(slot) + float2(0.55, 0)).x - corner.x;
        if (GUI.Button(Rect(corner.x, corner.y, width, 32), loaded ? "Unload" : "Load")) Toggle(slot);
    }
}

view Balls(Ball ball, mut Count count)
{
    Draw.Circle(ball.position, 0.1, Color(0.18, 0.83, 0.75));
    count.balls += 1;
}

view Total(Count count)
{
    Draw.SetScreen();
    Draw.Text($"{count.balls} balls, in the rooms that are loaded", float2(16, 14), 16, Color.white);
}
```



<a id="which-scene-owns-what"></a>

## Which scene owns what

A spawn joins the scene of the entity the code is running for. In a handler, that's the entity the event was sent to, so the floor above joins the arena it was spawned for. A spawn into a scene that's unloaded by the spawn's turn is never made, like the loot an enemy drops while its arena unloads. Code that isn't running for an entity, like a system that runs once per tick, spawns into no scene, and those entities live until they're destroyed.

A scene itself is never owned: it lives until it's unloaded, whoever loaded it.

Loaded scenes share their world: the same systems, singletons and `Time`.

<a id="heavy-preparation"></a>

## Heavy preparation

Put expensive deterministic setup inside a scene's `prepare(...)` block:

```csharp
singleton Geography
{
    int completed;
    int total;
}

scene Campaign
{
    int seed = 42;

    prepare(mut Geography geography)
    {
        geography.total = 3;
        GenerateTerrain(seed, geography);
        geography.completed = 1;
        GenerateRoads(seed, geography);
        geography.completed = 2;
        GenerateSettlements(seed, geography);
        geography.completed = 3;
    }
}
```

The generation functions above are game code. A scene has at most one block,
and parentheses are required even with no dependencies: `prepare() { ... }`.
Scene fields and methods are available directly; `this` is the scene's entity.
Other data uses the same explicit parameters as match handlers. A component
parameter belongs to the root and must be supplied to `Scene.Load`; singletons
and queries keep their ordinary meaning.

Preparation runs for the initial scene and for later loads, before `Spawned`.
Its spawns belong to the scene and exist before the scene's `Spawned` handlers.
The match stops advancing ticks while this machine prepares; `Time` does not
advance. On hosts with background workers, views and networking keep running.
Views can read consistent progress snapshots between completed top-level
preparation statements. Progress fields are ordinary game data: the engine
doesn't infer a percentage, and a long helper or loop need not publish an
intermediate update.

```csharp
bool loading = !Scene.IsPrepared(campaign);
bool playerReady = Scene.IsPrepared(campaign, player);
```

The one-argument form checks completion on this machine. The player form reads
readiness acknowledged through the server's ordered commands, so match code can
decide when to admit a player to gameplay. Missing, unloaded and non-scene
handles return false. Scenes without a block finish immediately; their players
still acknowledge readiness. Local scenes support the one-argument form and
use ordinary `Spawned` setup.
Read match readiness from match code and views; synchronous local event
handlers operate on their recorded event state.

Every peer with the complete match independently prepares the same committed
state. The server resumes when its own preparation finishes. Slower peers catch
up from buffered ticks, using normal state recovery if needed. Waiting for
players, deadlines and kicks are game policy. In visibility-enabled matches,
clients receive the permitted prepared result from the server, because they may
lack private generation inputs.

Preparation is deterministic match code. It can call synchronous helpers,
change declared match data, query and spawn. It cannot access local state,
await, start async tasks, or load another scene, including through helpers and
sent events. Start follow-up work in `Spawned`. Trusted C retains its ordinary
determinism and thread-safety responsibilities.

Heavy work starts only for committed loads. Completed preparation becomes the
baseline for subsequent prediction and rollback. Leaving the match discards
unfinished work. Hosts without a background provider execute preparation
synchronously; sharded matches currently reject preparation blocks.

<a id="private-scenes"></a>

## Private scenes

Scenes are public by default. Give a match scene root an ordinary `Visibility`
component to restrict the scene and every entity it owns:

```csharp
scene Hand
{
    PlayerID player;
}

event(PlayerJoined joined) DealIn()
{
    var group = Visibility.CreateGroup(Audience.Only(joined.player));
    Scene.Load(Hand { player = joined.player }, Visibility { group = group });
}
```

Use `Visibility.Set(group, audience)` to replace the scene's audience. The same
group can serve several scenes and ordinary entities. Audience changes are match
state, so only match code changes them. Local scenes belong to this machine and
do not take `Visibility`.

A scene whose group has `Audience.None` stays on the server. Including a player
supplies its current permitted state; excluding one conceals it. An entity's
group can restrict the scene audience further, and a component's policy can
restrict the entity audience further. These three scopes intersect; an inner
scope cannot broaden an outer one. See [State visibility](https://tide-engine.dev/game/visibility.md) for
shared groups and component policies. The server simulates the complete match
and corrects clients where hidden simulation affects their permitted state.
