Prefab code generation

A Prefab file is a scene and is compiled into JavaScript (or TypeScript) code. A regular scene file is compiled into a class that extends the Phaser.Scene class. It is a scene after all. However, the Prefab file is compiled into a custom object class.

The Prefab class generated by the scene compiler extends a game object class, like an Image, a BitmapText, etc… or another prefab class.

This is the code generated after compile the Dragon prefab:

class Dragon extends Phaser.GameObjects.Image {

    constructor(scene, x, y, texture, frame) {
        super(scene, x ?? 100, y ?? 100, texture || "dragon", frame ?? "dragon/flamming_00");

        this.scaleX = 0.7;
        this.scaleY = 0.7;
    }
}

Note the Prefab class extends the Phaser.GameObjects.Image class, because the prefab object is an Image.

The constructor of the Dragon class has the same arguments of the Image class, but by default, it uses the texture set in the prefab object. Also, in the body of the constructor, are set the properties modified in the prefab object:

this.scaleX = 0.7;
this.scaleY = 0.7;

When the scene compiler compiles a regular scene file, the prefab instance in it are generated as instances of the Prefab class:

class Level extends Phaser.Scene {

    constructor() {
        super("Level");
    }

    create() {
        ...

        // create the instance of the Dragon prefab class
        const dragon = new Dragon(this, 190, 120);
        // add the instance to the display list
        this.add.existing(dragon);
        // modify the 'angle' property of the instance
        dragon.angle = -30;
        ...
    }
}

Also, the Prefab class can be instantiated manually by you, at any time in your game. It is just a custom object class that looks like if you write it by hand.

Updated on