Prefabs API
Spawn exported prefab fragments into the active scene.
On this page
Use api.prefabs() to create exported prefabs in the currently loaded scene.
PrefabsAPI prefabs = api.prefabs();
Spawn a prefab’s main entity
When a prefab has one clear main entity, use requireFirst(...):
EntityRef enemy = api.prefabs().requireFirst("Enemy", 320f, 80f);
enemy.animation().play("idle");
first(...) returns an invalid EntityRef with entity ID -1 when the prefab creates no entity. requireFirst(...) expresses that at least one entity is expected and throws IllegalStateException when none is created.
Spawn every prefab entity
Use spawn(...) when you need all entities created by the prefab:
SpawnResult result = api.prefabs().spawn("Enemy", 320f, 80f);
Pass the exported prefab name without .pixfragment.json. The x and y values are world-space offsets added to the prefab’s transforms; they do not place every entity at exactly the same position.
Each prefab instance receives fresh entity identities for the active scene.
SpawnResult.createdEntityIds() returns an Artemis IntBag containing every created runtime entity ID:
IntBag created = result.createdEntityIds();
for (int i = 0; i < created.size(); i++) {
EntityRef entity = api.entities().ofEntityId(created.get(i));
entity.transform().moveBy(16f, 0f);
}
Use SpawnResult when you need every entity rather than relying on their creation order.
Spawn an already loaded fragment
Advanced loading code can instantiate a RuntimePrefabFragment directly:
SpawnResult result = api.prefabs().spawnFragment(fragment, 320f, 80f);
The fragment must use the Runtime’s current prefab schema. Normal gameplay usually uses spawn(name, x, y) with the exported file instead.
Make the prefab available
Prefab spawning requires a loaded project and an active scene. If gameplay will spawn the prefab later, add the prefab itself to Runtime Availability before loading the scene.
The prefab fragment and its required dependencies must be ready for that scene. This includes sprite assets, animations, and particle effects referenced by the prefab but not otherwise used there. Runtime does not prepare missing prefab resources on demand during gameplay.