Prefab Instancing in 1.2.0

Prefab Instancing in 1.2.0

Prefab instantiation is the process of creating objects and components from a .bin/.glb file.

Since the new instantiation method is based on the concept of multiscene, we recommend you have a quick look at our multiscene blog post first.

Pre-1.2.0 

Instantiating a “prefab” was available via the (now deprecated) append method:

1const promises = [];
2for (let i = 0; i < 100; ++i) {
3    promises.push(await engine.scene.append('Zombie.bin'));
4}
5await Promise.all(promises);

This API comes with limitations:

  • The scene needs to be downloaded, and parsed 100 times
  • Each Zombie.bin creates new meshes, textures, and materials

Let’s see how Wonderland Engine 1.2.0 helps solving those issues!

Instancing 

Any scene loaded via loadScene can be the recipient of an instantiation:

1const mainScene = await engine.loadMainScene('Scene.bin');
2const zombie = await engine.loadPrefab('Zombie.bin');
3
4// Create a horde of zombies
5for (let i = 0; i < 100; ++i) {
6    const {root} = mainScene.instantiate(zombie);
7}

Since the result is an Object3D instance, you can modify the hierarchy as follows:

1const {root} = mainScene.instantiate(zombie);
2// `root` is the Object3D parent of the entire `Zombie.bin` scene graph
3root.setScalingLocal([0.5, 0.5, 0.5]);

You can call instantiate() on active and inactive scenes. While the above example demonstrates how to use it on an active scene, instancing in an inactive scene works the same way:

1const zombie = await engine.loadPrefab('Zombie.bin');
2const zombieHead = zombie.findByName('Head')[0];
3zombieHead.addComponent(LookAtComponent);
4
5const nextScene = engine.load('NextScene.bin');
6
7// Only once instantiated, LookAtComponent.onActivate()
8// and LookAtComponent.start() are invoked.
9nextScene.instantiate(zombie);

GLTF 

Instantiation isn’t limited to the Wonderland Engine scene format (.bin), but can also be used with glTF:

1const avocado = await engine.loadGLTF('Avocado.glb');
2
3// Make an avocado salad
4for (let i = 0; i < 100; ++i) {
5    const {root} = scene.instantiate(avocado);
6}

GlTF prefabs also have extra methods to manage extensions. For more information, have a look at the PrefabGLTF API.

Note About Resources 

As mentioned in the multiscene blog post, resources are moved into the engine instance upon loading. This allows multiple scenes to reference the same resources, without duplicating memory.

Components created via instantiation thus:

  • Reference the same resources
  • Deleting a resource will make the instance reference a null entry

Going Further 

Here are a few links to help you start using instancing in your projects:

We can’t wait to see how the community will take advantage of instancing to build amazing experiences!

Last Update: May 19, 2024

Stay up to date.