For the complete documentation index, see llms.txt. This page is also available as Markdown.

Composites

Spawn a tree of entities and components at runtime from a composite file

A composite is a file that describes a tree of entities and components. Instead of writing code to create each entity one by one, you can store that structure in a composite file and spawn the whole thing with a single call.

You might already work with composites without realizing it:

  • Every scene has a main.composite file. It holds everything you added and configured visually in the Scene Editor. This file is loaded automatically when your scene starts.

  • Custom Items are saved as composite.json files. Each Custom Item is a composite that you can reuse across scenes.

This page covers how to spawn a composite from code at runtime, for example to spawn a Custom Item dynamically as part of your scene's logic.

Spawn a composite

Spawning a composite takes two steps: load the composite file, then spawn it. Loading is asynchronous and spawning is synchronous, so the pattern is always load-then-spawn:

export async function spawnBarrel() {
  const src = "barrel.composite";

  // 1. Load the composite from its file
  await engine.getCompositeProvider().loadComposite(src);

  // 2. Spawn it: creates all its entities and components
  const barrel = engine.addEntityFromComposite(src);
  return barrel;
}

engine.getCompositeProvider().loadComposite(src) reads the composite file and loads it into memory. In a normal scene built with @dcl/sdk, a composite provider is already set up for you, you reach it with engine.getCompositeProvider().

engine.addEntityFromComposite(src) then creates all the entities described in the composite, with all their components, and returns the root entity of the spawned tree. Use this returned entity to read or change components later, for example to reposition or remove the spawned item.

💡 Tip: To do the same thing without writing code, use the Spawn Entity action in the Scene Editor. See About spawning entities.

Position a spawned composite

Pass a transform option to addEntityFromComposite() to place the spawned composite at a specific position, rotation, or scale. This transform is applied to the root entity.

The transform fields (position, rotation, and scale) are all optional. Any field you leave out keeps the value stored in the composite.

Current limitation: nested composites

Spawning works for self-contained composites and Custom Items. A composite can reference another composite from one of its entities, but loading does not recurse into those nested references yet.

If a spawned composite's root references another composite (anything other than main.composite, the only composite bundled with your scene), it fails to instantiate. For now, keep the composites you spawn self-contained.

Last updated