Spawn prefabs

You can spawn prefabs at runtime while the game is being played. This can be useful to for procedurally adding more complex objects to the scene. For example, if you have a house created in a prefab made up of many different meshes and even actors that reference other actors within the prefab, you can spawn all of this together.

To spawn a prefab, you first need to get the prefab asset from the AssetLoader service. With the prefab, you can call the spawnPrefab function with optional parameters for world position and rotation. This method is asynchronous and returns a promise as it loads any resources necessary to create the prefab and calls any actors onInit method. The returned promise contains a PrefabInstance which later can be used to remove the prefab, removing any objects included in the prefab from the scene and removing actors.

import { Service, GameInstance, inject, World, AssetLoader } from '@hology/core/gameplay';
import { Vector3 } from 'three';

@Service()
class Game extends GameInstance {
  private world = inject(World)
  private assetLoader = inject(AssetLoader)

  async onStart() {
    const prefab = await this.assetLoader.getPrefabByName('test prefab')
    const instance = await this.world.spawnPrefab(prefab, new Vector3(0,0,0))

    setTimeout(() => {
      this.world.removePrefab(instance)
    }, 1000)
  }
}

export default Game

Last updated