Scripting
Scripts are the heart of interactivity in PlayCanvas. They're reusable pieces of code that you attach to Entities to define behaviors, handle user input, manage game logic, and bring your projects to life.
Using the Editor?
If you're using the PlayCanvas Editor, check out the Editor Scripting section to learn about managing scripts, the code editor, VS Code integration, and hot reloading.
Two Scripting Systems
PlayCanvas supports two scripting approaches:
- ESM Scripts (
.mjsfiles) — Modern ES Module-based scripts using class syntax. Recommended for new projects. - Classic Scripts (
.jsfiles) — The original PlayCanvas scripting system using prototype-based syntax.
Both systems can coexist in the same project, allowing you to migrate gradually or use whichever approach fits your needs.
Quick Example
Here's a simple script that rotates an entity:
- ESM (Recommended)
- Classic
import { Script } from 'playcanvas';
export class Rotate extends Script {
static scriptName = 'rotate';
/** @attribute */
speed = 10;
update(dt) {
this.entity.rotate(0, this.speed * dt, 0);
}
}
var Rotate = pc.createScript('rotate');
Rotate.attributes.add('speed', { type: 'number', default: 10 });
Rotate.prototype.update = function(dt) {
this.entity.rotate(0, this.speed * dt, 0);
};
In This Section
- Getting Started — Basic script structure and syntax.
- ESM Scripts — Modern scripting with ES Modules.
- Script Lifecycle — When and how script methods are called.
- Application Lifecycle — Understanding app initialization and frame updates.
- Script Attributes — Exposing configurable properties.
- Engine API — Key classes and patterns.
- Events — Communication between scripts.
- Debugging — Tools and techniques for troubleshooting.
- Migration Guide — Upgrading from classic to ESM scripts.