Prefabs are assets that can be considered as templates storing entities (including their child entities and components) data. Prefabs allow developers to create and update this template, which can then be instantiated into the scene as needed.
If you want to reuse entities configured in a specific way across multiple locations in a scene or multiple scenes in a project, such as non-player characters (NPCs), props, or landscapes, you should convert this game object into a prefab. This approach is better than simply copying and pasting game objects because prefabs can keep all copies synchronized.
The same prefab can be used in multiple scenes, and any modifications to the prefab can be automatically applied to all instances.
Prefabs can package complex entities (including their child entities and components) into a single asset, making them easy to manage and organize.
By using prefabs, you can ensure that objects used in different scenes or different parts maintain consistency.
Extensive use of prefabs can reduce repetitive work, making the development process more efficient.
There are two ways to create a prefab:
There are two ways to update a prefab:
Drag the entity from the Hierarchy Panel onto an existing prefab asset in the Asset Panel. The prefab asset will be updated with the new content, and all instances created from this prefab will also be updated with the latest content.
The entity can also be an instance of this prefab.
Instances of a prefab are generated based on the prefab template. All instances will change as the template changes, but each instance may have its own modifications: addition, deletion, or updates of child entities and components. To make the modifications of an instance part of the template, you can do the following:
If you want a prefab instance to disconnect from the prefab so that it no longer changes with the prefab, you can unlink the prefab instance.
A prefab is an asset, and it can be deleted just like other assets. Note that when a prefab is deleted, there are two ways to handle its instances:
The engine object of a prefab asset is PrefabResource. After loading a prefab (Asset Loading), you can instantiate it using the instantiate method.
engine.resourceManager
.load({ url: "Prefab's URL", type: AssetType.Prefab })
.then((prefab: PrefabResource) => {
const prefabInstanceEntity = prefab.instantiate();
scene.addRootEntity(prefabInstanceEntity);
});