# 3. Additive Scene Streaming with SceneManager
Part of [[Open-World Streaming]]. Previous: [[2. WorldGrid Cells and Hysteresis]]. Next: [[4. Streaming Cells with Addressables]].
> [!warning] Code not compiled in Unity
> Type-checked against 6000.5.8f1 (with Addressables 2.9.1 for the shared streamer). Not run in a scene.
## 3.1 The source interface
The streamer shouldn't know whether a cell comes from the scene list, Addressables, or a test double. So it talks to two small interfaces:
```csharp
// Assets/Scripts/Streaming/CellSources.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>One in-flight or resident cell scene, independent of how it was loaded.</summary>
public interface ICellHandle
{
CellCoord Cell { get; }
bool IsLoaded { get; }
bool Failed { get; }
Scene Scene { get; }
/// <summary>Starts unloading. Only valid once IsLoaded or Failed.</summary>
void BeginUnload();
bool IsUnloaded { get; }
}
/// <summary>Where cell scenes come from: Build Profile scene list, Addressables, or a test double.</summary>
public interface ICellSceneSource
{
bool Exists(CellCoord cell);
ICellHandle BeginLoad(CellCoord cell);
}
/// <summary>
/// Cells are ordinary scenes named prefix + "x_z" in the active Build Profile's scene list,
/// loaded with SceneManager.LoadSceneAsync(..., LoadSceneMode.Additive).
/// </summary>
public sealed class BuildListCellSource : ICellSceneSource
{
readonly string _prefix;
readonly Dictionary<CellCoord, bool> _existsCache = new Dictionary<CellCoord, bool>();
public BuildListCellSource(string prefix) => _prefix = prefix;
public bool Exists(CellCoord cell)
{
if (!_existsCache.TryGetValue(cell, out var exists))
{
exists = Application.CanStreamedLevelBeLoaded(cell.SceneName(_prefix));
_existsCache[cell] = exists;
}
return exists;
}
public ICellHandle BeginLoad(CellCoord cell) => new Handle(cell, cell.SceneName(_prefix));
sealed class Handle : ICellHandle
{
readonly string _name;
readonly AsyncOperation _load;
AsyncOperation _unload;
bool _unloadRequested;
public Handle(CellCoord cell, string name)
{
Cell = cell;
_name = name;
_load = SceneManager.LoadSceneAsync(name, new LoadSceneParameters(LoadSceneMode.Additive));
Failed = _load == null;
}
public CellCoord Cell { get; }
public bool Failed { get; }
public bool IsLoaded => !Failed && _load.isDone && !_unloadRequested;
public Scene Scene => SceneManager.GetSceneByName(_name);
public void BeginUnload()
{
if (_unloadRequested)
return;
_unloadRequested = true;
if (Failed)
return;
var scene = Scene;
if (scene.IsValid() && scene.isLoaded)
_unload = SceneManager.UnloadSceneAsync(scene);
}
public bool IsUnloaded => _unloadRequested && (_unload == null || _unload.isDone);
}
}
```
### Notes on `BuildListCellSource`
- **`Application.CanStreamedLevelBeLoaded(name)`** returns true if a scene with that name is in the active Build Profile's scene list. The result is cached per cell, so you don't re-check every frame.
- **`LoadSceneAsync(name, new LoadSceneParameters(LoadSceneMode.Additive))`** returns an `AsyncOperation`, or `null` if the scene can't be found. A `null` result is treated as `Failed`.
- **`GetSceneByName`** finds the loaded scene again for unloading. That's why cell names must be unique.
- **Unload is only legal once the load finished.** `SceneManager.UnloadSceneAsync` on a scene that's still loading isn't supported. The streamer enforces this (below) instead of each source guessing.
## 3.2 The streamer
```csharp
// Assets/Scripts/Streaming/CellStreamer.cs
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Loads cell scenes around a target and unloads them behind it, with hysteresis,
/// a concurrency cap and a per-frame start budget. Source is pluggable (Build list or Addressables).
/// Reads true world position through FloatingOrigin so it keeps working after origin shifts.
/// </summary>
public sealed class CellStreamer : MonoBehaviour
{
public enum SourceKind { BuildProfileScenes, Addressables }
[SerializeField] Transform target;
[SerializeField] SourceKind source = SourceKind.BuildProfileScenes;
[SerializeField] string scenePrefix = "World_";
[SerializeField] string addressablesLabel = "world-cells";
[SerializeField, Min(1f)] float cellSize = 256f;
[SerializeField, Min(0)] int loadRadius = 1;
[SerializeField, Min(0)] int unloadRadius = 2;
[SerializeField, Min(1)] int maxConcurrentLoads = 2;
[SerializeField, Min(1)] int maxStartsPerFrame = 1;
ICellSceneSource _source;
readonly Dictionary<CellCoord, ICellHandle> _resident = new Dictionary<CellCoord, ICellHandle>();
readonly List<ICellHandle> _unloading = new List<ICellHandle>();
readonly HashSet<CellCoord> _placed = new HashSet<CellCoord>();
readonly List<CellCoord> _toLoad = new List<CellCoord>();
readonly List<CellCoord> _toUnload = new List<CellCoord>();
readonly List<GameObject> _scratch = new List<GameObject>();
CellCoord _lastCenter = new CellCoord(int.MinValue, int.MinValue);
bool _dirty = true;
public CellCoord CurrentCell => _lastCenter;
public int ResidentCount => _resident.Count;
void Start()
{
if (source == SourceKind.Addressables)
{
var a = new AddressablesCellSource(scenePrefix);
a.Initialize(addressablesLabel);
_source = a;
}
else
{
_source = new BuildListCellSource(scenePrefix);
}
}
void Update()
{
if (_source == null || target == null)
return;
if (_source is AddressablesCellSource a && !a.IsReady)
return;
FloatingOrigin.WorldXZ(target.position, out var wx, out var wz);
var center = WorldGrid.CellAt(wx, wz, cellSize);
if (!center.Equals(_lastCenter))
{
_lastCenter = center;
_dirty = true;
}
PlaceFinishedLoads();
ReapUnloads();
if (_dirty)
{
WorldGrid.Plan(center, loadRadius, unloadRadius, _resident.Keys, _source.Exists, _toLoad, _toUnload);
_dirty = _toLoad.Count > 0; // keep planning until everything in range has started
for (var i = 0; i < _toUnload.Count; i++)
TryBeginUnload(_toUnload[i]);
}
var inFlight = CountInFlight();
var started = 0;
for (var i = 0; i < _toLoad.Count && inFlight < maxConcurrentLoads && started < maxStartsPerFrame; i++)
{
var cell = _toLoad[i];
if (_resident.ContainsKey(cell))
continue;
_resident[cell] = _source.BeginLoad(cell);
inFlight++;
started++;
}
}
int CountInFlight()
{
var n = 0;
foreach (var h in _resident.Values)
{
if (!h.IsLoaded && !h.Failed)
n++;
}
return n;
}
void PlaceFinishedLoads()
{
foreach (var kv in _resident)
{
var h = kv.Value;
if (!h.IsLoaded || _placed.Contains(kv.Key))
continue;
// Cell content is authored at true world coordinates; bring it into the shifted frame
// and register it so later origin shifts move it too.
FloatingOrigin.Place(h.Scene, _scratch);
_placed.Add(kv.Key);
}
}
void TryBeginUnload(CellCoord cell)
{
if (!_resident.TryGetValue(cell, out var h))
return;
if (!h.IsLoaded && !h.Failed)
{
_dirty = true; // still loading; try again on a later frame
return;
}
if (h.IsLoaded)
FloatingOrigin.Forget(h.Scene);
h.BeginUnload();
_resident.Remove(cell);
_placed.Remove(cell);
_unloading.Add(h);
}
void ReapUnloads()
{
for (var i = _unloading.Count - 1; i >= 0; i--)
{
if (_unloading[i].IsUnloaded)
_unloading.RemoveAt(i);
}
}
}
```
### How a frame goes
1. **Where am I?** `FloatingOrigin.WorldXZ` turns the target's local position into true world coordinates (part 5; with no shift yet, the offset is 0). `WorldGrid.CellAt` gives the cell.
2. **Finish what arrived.** `PlaceFinishedLoads` hands each newly loaded scene to `FloatingOrigin.Place`, which moves it into the current shifted frame and registers it for future shifts.
3. **Plan only when needed.** `_dirty` is set when the cell changes, and it stays set while there are cells waiting to start or to unload. Planning isn't expensive, but a dirty flag makes "nothing changed" cost nothing (*Dirty Flag*, [[Game Programming Patterns (Review)]]).
4. **Unload first, then load.** Releasing memory before asking for more matters on Quest. A cell that's still *loading* when it falls out of range is left alone and retried on a later frame.
5. **Start loads under budget.** At most `maxConcurrentLoads` in flight and `maxStartsPerFrame` new ones per frame, nearest first.
## 3.3 Set it up
1. In `World_Bootstrap`, create an empty GameObject called `Streaming`. Add **CellStreamer** and **FloatingOrigin** (part 5; leave its threshold high, for example 100000, until then).
2. **CellStreamer:** Target = the player. Source = `BuildProfileScenes`. Prefix `World_`. Cell Size 256, Load Radius 1, Unload Radius 2, Max Concurrent Loads 2, Max Starts Per Frame 1.
3. **FloatingOrigin:** Focus = the player.
4. Press Play. The Hierarchy shows `World_0_0` first, then its eight neighbours. Walk (or move the player in the Scene view) east past x = 256: `World_2_*` appears. Walk back, and nothing unloads until you're two cells away.
5. Watch **Profiler → CPU** while a cell appears. The integration cost lands on the main thread at the end of the load (look for asset-integration markers and your scripts' `Awake`).
### Smoothing hitches
- `Application.backgroundLoadingPriority = ThreadPriority.Low` gives the background load less of each frame. Loads take longer but hitch less. Set it from the bootstrap scene when gameplay starts, and set it to `High` behind a loading screen.
- Keep cell `Awake`/`OnEnable` cheap. Heavy setup in a cell (building a NavMesh, generating a mesh) should be spread over frames, or done offline.
- After unloading several build-list cells, call `Resources.UnloadUnusedAssets()` at a calm moment (it's expensive) so textures only those cells used are freed. Addressables (part 4) doesn't need this, because it frees bundles when their handles are released.
## 3.4 Cross-cell objects
- An NPC that walks out of its cell is still a child of that cell's scene. When the cell unloads, the NPC vanishes. Either keep NPCs in the bootstrap scene and spawn them from a pool ([[Object Pooling and Spawners]]), or move them with `SceneManager.MoveGameObjectToScene` when they cross a border.
- Inspector references **between** scenes aren't allowed. Use IDs: a door in `World_1_0` can name its key by a string or a ScriptableObject asset, and look it up at runtime.