✨ instantiatePrefab

What is it?

instantiatePrefab allows you to instantiate a copy of a Prefab stored in the project into the game at runtime.

A Prefab is a JSON file located in the project's prefab list:

prefabs/NAME.json

The engine loads that JSON, reconstructs the object, normalizes all its values, loads its script, registers it internally, and immediately executes Start().

πŸ“– Syntax

await instantiatePrefab(prefabName, x, y);

πŸ”§ What does a Prefab contain?

Each prefab is a JSON file containing all object data:

πŸš€ What does instantiatePrefab do automatically?

πŸ“˜ Basic example


// Instantiate the "EnemyBasic" prefab at position (200, 150)
const enemy = await instantiatePrefab("EnemyBasic", 200, 150);

This creates a fully functional copy of the prefab, with its script active if it has one.

πŸ“˜ Example with logic from a script


function Start(obj) {
  // Create an enemy next to the player when the game starts
  instantiatePrefab("ENEMY_FOLLOW", obj.x + 50, obj.y);
}

πŸ“˜ Example: projectile using a prefab


function Shoot(obj) {
  const bullet = await instantiatePrefab("BulletPrefab", obj.x, obj.y);
  bullet.vx = 400;
}

πŸ“Œ Important notes

- Prefabs are the recommended way to instantiate enemies, projectiles, power-ups and complex objects.
- Unlike instantiateObject, the Prefab already includes components, animations, sounds and script.
- Start() is executed immediately after instantiating the prefab, even if the game was already running.
- Prefabs allow reusing objects without duplicating script logic.

πŸ†š instantiatePrefab vs instantiateObject

Features instantiatePrefab instantiateObject
Uses project JSON βœ” Yes ❌ No
Includes components βœ” Yes ❌ Only if provided manually
Includes default image/animations βœ” Yes ❌ No
Includes associated script βœ” Yes βœ” Only if provided
Automatically runs Start βœ” Yes βœ” Yes (new system)
Ideal for… enemies, projectiles, repeated objects one-off or procedural creation