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.
Two Scripting Systems
PlayCanvas supports two scripting approaches:
- ESM Scripts (
.mjs
files) - Modern ES Module-based scripts using class syntax. Recommended for new projects. - Classic Scripts (
.js
files) - 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);
};
What You'll Learn
Fundamentals
Core concepts that apply to all PlayCanvas scripts:
- Getting Started - Basic script structure and syntax
- ESM Scripts - Modern scripting with ES Modules
- Script Lifecycle - When and how script methods are called
- Script Attributes - Exposing configurable properties
- Calling the Engine API - Key classes and patterns
- Events - Communication between scripts
Editor Integration
Working with scripts in the PlayCanvas Editor:
- Managing Scripts - Creating and organizing script files
- Code Editor - Using the built-in code editor
- VS Code Extension - Enhanced development workflow
- Hot Reloading - Live code updates
Debugging
Tools and techniques for troubleshooting your scripts:
- Console Logging - Basic debugging with console output
- Browser Dev Tools - Advanced debugging techniques
tip
New to PlayCanvas scripting? Start with Getting Started to learn the basics, then explore ESM Scripts for the modern approach.