Skip to content

Loading assets on demand ​

A big game doesn't have to download everything before it starts. A script can load what a level, a character or a menu needs when it needs it, show a bar while it does, and let go of it afterwards.

What loads when ​

A project's Asset loading setting (Environment panel) decides what's fetched before the Start button:

SettingBefore StartAfter Start
Load everything up front (default)The scene's files, and every prefab scripts point at with everything inside themFiles only a script names load when it asks for them
Load the scene, the rest on demandOnly the files the scene's entities useEverything else loads when a script asks, or when something spawns
Ask the playerWhichever the player picks, with the real size of each choice beside itThe same

Choosing Download everything fetches every file the game ships, including those only a script names. Models and sounds are kept as bytes, unparsed, for the rest of the visit, so loading one later needs no second download. Load as you play fetches only what the scene's entities use.

The player's choice is remembered on their device, and they can change it from the Start screen. Whatever the setting, the calls below work the same: a file that's already here costs nothing.

An entity in the scene always loads its file. To keep something out of the first download, put it in a prefab and point a script at the prefab, or name its file in a script.

Loading a level behind a bar ​

Load the prefab and everything inside it, then spawn it. Spawning finds every file ready, so it appears at once.

ts
import { Behaviour, type AssetInput } from "@relu-interactives/spatial-ecs";

export default class LevelLoader extends Behaviour {
  data = {
    level: { path: "", type: "prefab" } as AssetInput,
  };

  private bar: HTMLDivElement | null = null;
  private levelId: number | null = null;

  init() {
    this.bar = document.createElement("div");
    this.bar.style.cssText =
      "position:fixed;left:0;bottom:0;height:6px;width:0;background:#fff";
    document.getElementById("relu-ui")?.append(this.bar);
    void this.enterLevel();
  }

  private async enterLevel() {
    try {
      await this.loadAssets(this.data.level, {
        onProgress: ({ fraction }) => {
          if (this.bar) this.bar.style.width = `${fraction * 100}%`;
        },
      });
      this.levelId = await this.spawnPrefab(this.data.level);
    } catch (error) {
      // Names every file that failed. Calling loadAssets again retries them.
      console.error(error);
    }
    this.bar?.remove();
  }

  leaveLevel() {
    if (this.levelId !== null) this.despawn(this.levelId);
    this.levelId = null;
    this.releaseAssets(this.data.level);
  }

  dispose() {
    this.bar?.remove();
  }
}

Loading files ​

this.loadAssets(files, { onProgress }) takes one file or a list, each a path or an AssetInput field, and resolves when they're ready.

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export default class Armoury extends Behaviour {
  async unlock(weapon: string) {
    await this.loadAssets([
      `assets/weapons/${weapon}.glb`,
      `assets/weapons/${weapon}-icon.png`,
      "assets/sfx/fighter.soundbank.json",
    ]);
  }
}
FileWhat loading doesgetLoadedAsset gives
.glb, .gltfParses it into the shared model cache that model entities readGLTF
.prefabLoads it and every model, image, sound and nested prefab inside itPrefabAsset
ImagesLoads a textureTHREE.Texture
.soundbank.jsonThe same as this.loadSoundBank, so this.playSlot works
Anything else (audio, .fbx, .hdr)Fetches the bytes, which the engine's loaders read when they want the fileArrayBuffer

Leave videos to their VideoComponent: they stream, and loading one here would hold the whole file in memory.

  • Paths start at assets/ and work the same in Preview and a published build. An AssetInput field already holds the right path.
  • Asking twice is fine. Calls for one file share one load, and that includes a model entity loading the same file. A file that's already loaded costs nothing.
  • Progress gives { loaded, total, fraction }: files finished, files asked for, and 0 to 1 for a bar. fraction follows bytes where the server says how many there are, and it never steps backwards.

Spawning before a file has loaded ​

You don't have to wait. A model entity appears when its file arrives, so a script can spawn first and let it pop in. Use loadAssets first when you'd rather it arrive whole.

If a model entity's file failed, loading that file again brings the entity back.

Asking what's ready ​

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";
import * as THREE from "three";
import type { GLTF } from "three/examples/jsm/loaders/GLTFLoader.js";
import { clone } from "three/examples/jsm/utils/SkeletonUtils.js";

export default class Trophy extends Behaviour {
  show() {
    if (!this.isAssetLoaded("assets/trophy.glb")) return;

    const gltf = this.getLoadedAsset<GLTF>("assets/trophy.glb");
    if (gltf) this.threeRef.object.add(clone(gltf.scene));

    const label = this.getLoadedAsset<THREE.Texture>("assets/trophy-label.png");
    if (label) label.colorSpace = THREE.SRGBColorSpace;
  }
}

A model's scene is shared, so mount a clone, never the scene itself. Set colorSpace on a texture you use for colour.

Letting go ​

this.releaseAssets(files) frees GPU memory and the bytes kept for each file. A file that's wanted again just loads again. Releasing a prefab releases what's inside it.

ts
import { Behaviour } from "@relu-interactives/spatial-ecs";

export default class LevelChange extends Behaviour {
  leave(rootId: number) {
    this.despawn(rootId);
    const { released, kept } = this.releaseAssets("assets/levels/forest.prefab");
    console.log(`Freed ${released.length}, kept ${kept.length}`);
  }
}

A model an entity still shows stays loaded and comes back under kept, and so does anything still loading. Despawn first, then release. A prefab frees what it can and holds on to the rest, so two levels can share a player model: release the prefab again once what was on screen has gone.

A phone that runs out of memory reloads the page, so a game with big levels should let the last one go before loading the next.

When a file fails ​

The rest of the files still finish. Then loadAssets rejects with an AssetLoadError: its message names every file that failed and why, and failures lists them as { url, message }. Nothing failed stays cached, so calling again retries just those.

ts
import { AssetLoadError, Behaviour } from "@relu-interactives/spatial-ecs";

export default class Retry extends Behaviour {
  async load(files: string[]) {
    try {
      await this.loadAssets(files);
    } catch (error) {
      if (error instanceof AssetLoadError) {
        for (const { url, message } of error.failures) {
          console.warn(url, message);
        }
      }
    }
  }
}

Publishing ​

A publish ships the files a project uses, and that includes files only a script names: a full path, a file name only one asset has, a folder, or a name built as the script runs (`assets/weapons/${weapon}.glb`). AssetInput fields count too. The Project size panel shows what ships.