Skip to main content

Code scripts (JavaScript)

Most games can be made with behaviors and event sheets alone. When you want more control, write a small JavaScript script. Scripts and event sheets work together: they share variables, and both can find, move, create and destroy objects.

Kinds of script​

KindWhere it runsCreate it
πŸ“œ Object scriptOn every object that has a Code script component with it. One copy runs per object, and gets that object as entity.Logic β†’ Code scripts β†’ + New β†’ Object script, or Inspector β†’ οΌ‹ Add component β†’ Code script β†’ New script…
🌍 Game scriptOnce for the whole scene.Logic β†’ Code scripts β†’ + New β†’ Game script
πŸ“š LibraryNowhere on its own: other scripts import what it exports. See Share code with libraries.Logic β†’ Code scripts β†’ + New β†’ Library
πŸ›  Editor scriptOnly in the editor: your own menu commands, Inspector buttons and gizmos. Never in the game. See Editor scripts.Logic β†’ Code scripts β†’ + New β†’ Editor script
A Code script component on an object
A Code script component on an object
Choose or create the script
Choose or create the script

Fields on the Code script component are values you can set per object in the Inspector (e.g. a different speed per enemy). A script declares them with export let speed = 2 and reads them as its own variables; see Fields in the Inspector.

The code editor​

Tap ✏️ Edit code on the component, or a script in the Logic tab.

+ New β†’ Object or Game script
+ New β†’ Object or Game script
The code editor
The code editor
Snippets
Snippets
API help
API help
  • Autocomplete knows the real types: after entity.behavior('car'). it lists the Car's settings and readings, after entity.component('light'). the light's, and the same for your fields, data table rows, another script's exports (getScript('Enemy').), three.js and Rapier. Parameter hints show while you type a call, and holding on a name shows what it is.
  • Inside quotes it offers the names that fit that spot: behaviors, components, events and controls, and your project's objects, tags, scenes, variables, buttons, sounds, images, fonts and tables. game.find(' lists your objects; audio.play(' your sounds.
  • Mistakes are underlined as you type: a name that doesn't exist, the wrong number of arguments, a missing library. They never stop the game from running. A TypeScript script is checked in full (see TypeScript).
  • The key bar above the phone keyboard has the symbols code needs: { } ( ) [ ] ; . = " ' => + - * / < > ! & | , : ?, Tab, undo, redo and cursor keys.
  • Snippets inserts ready-made code (move with the joystick, jump, collect coins, follow the player…).
  • API opens the whole script API with a search box. Everything is also in the Scripting API reference.
  • Saved automatically as you type.
  • Syntax errors show in a yellow bar with the line number as you type. Runtime errors (while playing) show in a red bar and highlight the line; tap the bar to jump to it.
  • A runtime error names the object it happened on, once per object (the first three objects per script), so one broken enemy out of fifty is easy to find. Errors inside a timer or after an await are reported the same way.

The type information is a download the editor fetches the first time you open a script; until it arrives the editor still completes the basic API.

Lifecycle functions​

Define any of these; the engine calls them. function update(dt) and export function update(dt) both work.

FunctionWhenObjectGame
start()Once, when the scene startsβœ”βœ”
update(dt)Every frame, before physics. dt = seconds since the last frameβœ”βœ”
lateUpdate(dt)Every frame, after physicsβœ”
fixedUpdate(dt)On every physics step (60 a second, dt is always 1/60), whatever the frame rateβœ”βœ”
onEnable()Before start(), and each time this object is switched on againβœ”βœ”
onDisable()This object is switched off, or about to be destroyedβœ”βœ”
onTriggerEnter(other)This object entered, or was entered by, a trigger (other); same as onCollision when one of the two is a triggerβœ”
onTriggerStay(other)Every frame while it overlaps a triggerβœ”
onTriggerExit(other)It left the triggerβœ”
onCollision(other)This object started touching otherβœ”
onCollisionEnd(other)This object stopped touching otherβœ”
onTap()The player tapped this objectβœ”
onClick()This UI button was tapped (game scripts get onClick(button) for every button)βœ”βœ”
onValueChanged(value)This slider or scrollbar moved (a number), this toggle switched (true / false), this dropdown's option was picked (its index) or this Input field was typed in (its text); game scripts get onValueChanged(element, value)βœ”βœ”
onSubmit(text)Enter was pressed in this Input field (game scripts get onSubmit(field, text))βœ”βœ”
onEndEdit(text)The player stopped typing in this Input field (game scripts get onEndEdit(field, text))βœ”βœ”
onHTMLClick(id, target)Something inside this HTML element was clicked; id is the clicked part's id (game scripts get onHTMLClick(element, id, target))βœ”βœ”
onHTMLChange(id, value, target)A form part inside this HTML element changed; value is its text, 1 / 0 for a checkbox, or a number (game scripts get onHTMLChange(element, id, value, target))βœ”βœ”
onArrived()This object reached the point of its entity.moveTo() (game scripts get onArrived(object) for every object)βœ”βœ”
onDestroy()This object is about to be removedβœ”
onGameSaved(slot)The game was saved in a slot (game.saveGame, the Save game block)βœ”βœ”
onGameLoaded(slot)A saved game came back: start() has run on the rebuilt scene and the object's variables and position are the saved ones. Set up here what the save does not hold (see save slots)βœ”βœ”

Variables declared at the top of a script keep their values between frames (one set per object for object scripts):

let timer = 0;

function update(dt) {
timer += dt;
if (timer > 3) { timer = 0; game.log('3 seconds passed'); }
}

Timers: wait, after, every​

Three helpers do something later without counting seconds yourself:

after(2, () => entity.destroy()); // once, 2 seconds from now
const stop = every(1, () => game.spawn('Coin')); // again and again; stop() ends it

async function start() { // or write it top to bottom
entity.setText('3'); await wait(1);
entity.setText('2'); await wait(1);
entity.setText('1'); await wait(1);
entity.setText('GO!');
}
  • They count game time: they wait while the game is paused and follow game.timeScale (slow motion slows them too).
  • They belong to the object of the script: when it is destroyed its timers are dropped, and a function waiting in await wait(…) stops there. They wait while the object is disabled, and end with the scene.
  • after and every return a function that cancels them.
  • In a game script or a library, game.after(seconds, fn, owner?) and game.every(seconds, fn, owner?) do the same and take the object to belong to (or none).

Print while testing​

console.log('hp', hp), console.warn(…) and console.error(…) in a script write to the Debug console (🐞 in Play mode), which is the only console there is on a phone. game.log(…) does the same and also shows the message on screen for a moment; game.consoleLog(…) is the console only.

What a script can use​

NameWhat it is
entityThe object this script is on (object scripts). Also the type of other in collisions and of results from game.find().
gameThe running game: find/spawn/destroy objects, variables, scenes, camera, raycasts, saving, data tables (game.table('Item')).
inputJoystick (input.axis), buttons (input.isDown('jump')), touches, swipes, keys.
audioaudio.play('Coin'), audio.stop().
varsA storage object for the script.
fieldThe kinds of field: export let target = field.object(), field.image(), field.list(…)…
helperslerp, clamp, random, randomInt, deg2rad and JavaScript’s Math.
timerswait(seconds), after(seconds, fn), every(seconds, fn). See Timers.
consoleconsole.log() writes to the Debug console. See Print while testing.
THREEThe three.js library, for advanced effects. See three.js.
importCode from your libraries: import { roll } from 'Dice'.

A variable of your own with one of these names hides the engine's in that part of the script: const wait = wait(1) stops with an error, and the editor underlines it. Give yours another name.

Full list: Scripting API.

Fields in the Inspector​

What a script exports with export let at its top is a field, like a public field in Unity: every object that uses the script shows it in the Inspector with its own value, and the script reads it as its own variable.

export let speed = 2; // number, text or true / false
export let target = field.object(); // another object in the scene (or null)
export let icon = field.image(); // a picture from Files
export let hit = field.sound(); // a sound from Files
export let drop = field.prefab(); // a prefab
export let kind = field.choice('Sword', 'Potion', 'Key'); // a dropdown: the chosen word
export let tint = field.color('#ff8800'); // a colour
export let loot = field.data('Item'); // a row of a data table (or null)
export let items = field.list(Item); // a list you add to, remove from and reorder in the Inspector
export let lamp = field.component('light'); // an object's light
export let hp = field.behavior('health'); // an object's Health behavior
export let enemy = field.script('Enemy'); // an object's Enemy script

function update(dt) {
entity.translate(0, 0, speed * dt); // the value set on this object
}

As the script starts, each field gets the value set on its object, in place of the one written in the code. After that it is an ordinary variable: change it, and other scripts can read and change it through getScript().

field.image(), field.sound() and field.prefab() give you the file: icon.name is "Coin.png", and icon is null when nothing is picked. Hand it to anything that takes a file: entity.setUIImage(icon) shows the picture, audio.play(hit) plays the sound, and game.spawn(drop) creates the prefab.

field.component(…), field.behavior(…) and field.script(…) work like a Unity field of type Light or Health. In the Inspector you pick an object from those that have that component, behavior or script, and the script gets that object's light, behavior or script directly:

function start() {
lamp.intensity = 2; // the light of the object picked in the Inspector
hp.damage(1); // its Health behavior
enemy.hp = 5; // what its Enemy script exports, its fields among them
}

A field that holds an object keeps holding it after the object is destroyed: check target.destroyed before using one that may be gone.

Not a field:

  • export const: a constant.
  • A name that starts with _ (export let _hp = 3).
  • A value worked out when the script starts (export let hp = game.getVar('hp')), and functions and arrays.

These are still exported to other scripts. let without export is the script's own.

Every kind of field is on field, so type field. to see them all. Your own variables can be called image, data, color, list or props: those names are yours.

Your own types​

A field can be a class written in the script. Its fields become the fields of every list row, like a serializable class in Unity:

class Item {
name = 'Item';
icon = field.image();
kind = field.choice('Weapon', 'Potion', 'Key');
stack = 1;
use() { return this.name + ' x' + this.stack; }
}

export let bag = field.list(Item);
export let best = new Item();

function start() {
for (const item of bag) game.log(item.use()); // real Item objects: methods work
}

Write the class at the top of the script (starting in the first column), or put it in a library and import { Item } from 'Items'. The Inspector builds one new Item() to read the fields, so keep the class light. Classes and lists nest up to five levels.

Saving lists and objects​

Variables (game.setVar, entity.setVar, vars) and game.save / game.load hold numbers, text, true / false and lists and objects of those, so a whole backpack can be one variable or one save:

game.save('bag', [{ id: 'Sword', n: 1 }, { id: 'Potion', n: 3 }]);
const bag = game.load('bag'); // plain objects: Object.assign(new Item(), bag[0]) rebuilds a class

Event sheets see such a variable as its JSON text.

To keep the whole game rather than one value, use a save slot: game.saveGame('mysave') and game.loadGame('mysave') store and rebuild the scene with every object and variable; game.hasSaveGame('mysave') tells whether a Continue button should show.

Pick objects​

game.select('Enemy') or game.select('#enemy') gives every live object with that name or tag. game.query(…) takes the same selector (or a list of objects) and gives a set you narrow step by step, the way picking works in an event sheet. Each step returns a new set, so you can keep one and filter it two ways.

const target = game.query('#enemy')
.withVar('hp', '>', 0) // an instance variable test: ==, !=, <, <=, >, >= (two arguments means ==)
.within(entity, 12) // closer than 12 m
.nearest(entity) // the closest one
.first(); // an object, or null

game.query('Coin').each((c) => c.setVar('taken', true));
game.query('Slot').withVar('empty', true).random();
StepGives
where(fn), withTag(tag), withVar(name, op?, value), within(object, metres)Fewer objects.
nearest(to, count = 1), farthest(to, count = 1)The closest or furthest, in that order.
sortBy(variable or fn), take(n)Reordered or shortened.
each(fn)Does something to each, then gives the set back.
first(), last(), nth(i), random()One object, or null.
toArray(), length, map(fn), some(fn), for (const e of set)Plain JavaScript.

game.first('Player') is the short form of game.query('Player').first(). A tag is how objects form a family: give every kind of enemy the tag enemy and #enemy picks them all.

TypeScript​

Write a script in TypeScript by choosing it when you make the script (+ New script β†’ Language), or use Convert to TypeScript in the script's β‹― menu. Interfaces, enums, type annotations, generics and as all work, and the editor colours them.

interface Stack { id: string; n: number }
const slots: (Stack | null)[] = Array(12).fill(null);

export function add(id: string, n: number = 1): number { /* … */ return 0; }

The editor checks the types as you type and underlines what doesn't fit: a number where text is expected, a setting a behavior doesn't have, a function called with the wrong arguments. A JavaScript script is only told about clear mistakes (a name or member that doesn't exist, the wrong number of arguments, a missing library); a TypeScript script is checked in full.

A problem the editor underlines never stops the game from running. Before the game runs, and when you export it, the types are removed and every TypeScript script becomes plain JavaScript with each line where it was, so an error still points at the line you wrote, and the game runs exactly as a JavaScript one does. Convert to JavaScript removes the types for good.

The converter and the checker are downloads the editor fetches only when they are needed, and a player's phone never loads them.

Completion knows what each field holds, the columns of a data table row (game.table('Item').get('Sword').), and what another script exports.

Messages between scripts​

game.events sends named messages, so scripts do not have to know about each other:

// Hud script
game.events.on('coinTaken', (n) => { score += n; });

// Coin script
game.events.emit('coinTaken', 1);

on returns a function that stops listening, once listens for one message, and emit returns how many listeners heard it. Pass an object as the third argument (game.events.on('hit', fn, entity)) and the listener ends with that object and waits while it is disabled. All listeners end with the scene.

Share code with libraries​

As a game grows, several scripts need the same code: a damage formula, a "find the nearest enemy" helper, the settings of every level. Put it in a library once and use it everywhere.

A library is a script whose **export**ed functions and values other scripts can use. It has no start() or update().

// Library named "Combat"
export const MAX_HEALTH = 100;

export function damage(target, amount) {
const hp = (target.getVar('health') ?? MAX_HEALTH) - amount;
target.setVar('health', Math.max(hp, 0));
if (hp <= 0) game.destroy(target);
}

export function nearest(from, selector) {
let best = null, bestDist = Infinity;
for (const e of game.select(selector)) {
const d = from.distanceTo(e);
if (d < bestDist) { best = e; bestDist = d; }
}
return best;
}

Then, in any object script, game script or event-sheet script block, import it by the library's name:

// Object script on a Turret
import { damage, nearest } from 'Combat';

let cooldown = 0;
function update(dt) {
cooldown -= dt;
const target = nearest(entity, '#enemy');
if (target && cooldown <= 0) { damage(target, 10); cooldown = 0.5; }
}

Good to know:

  • Names: import { damage as hit } from 'Combat' renames; import * as Combat from 'Combat' (or import Combat from 'Combat') gives the whole library, used as Combat.damage(…).
  • One copy: a library runs once per game, the first time something imports it. Its top-level variables are shared by every script that imports it, and keep their values when the scene changes, so a library is also a good place for game-wide state.
  • Libraries can import libraries, but not in a circle (A imports B imports A).
  • Libraries get game, input, audio, THREE and the helpers, like a game script; there is no entity, and their exports are not fields.
  • If the name is wrong, the error lists the libraries that do exist, with the line of the import.

Talk to other scripts and components​

A library is shared by the whole game. When the code belongs to one object (this enemy's health, this door's open/close), put it in that object's script and export what other scripts may use:

// Object script named "Enemy"
export let hp = 3;

export function hit(amount) {
hp -= amount;
if (hp <= 0) entity.destroy();
}

Any other script reaches it with getScript('Name') on that object:

// Object script on a Bullet
function onCollision(other) {
other.getScript('Enemy')?.hit(1); // ?. : does nothing if `other` has no Enemy script
entity.destroy();
}
  • Each object has its own copy: hitting one enemy doesn't change the others' hp.
  • Values are live: getScript('Enemy').hp is always the current value.
  • You can change them too: getScript('Enemy').hp = 5 changes the Enemy script's hp, as GetComponent<Enemy>().hp = 5 would in Unity. An exported const can't be changed, and neither can a function: both stop with an error that says so.
  • The script's fields are exports too: getScript('Enemy').speed = 3.
  • getScript() gives null when the object has no script of that name (upper/lower case doesn't matter). It works on entity too, to reach another script on the same object.
  • Only what is exported can be used; start, update and the other lifecycle functions stay private.
  • The editor underlines a name in quotes that names nothing (getScript('Enemey'), component('ligth'), game.table('Itme')) and suggests the one you probably meant.

To point at one particular object's script without looking it up, use a field.script('Enemy') field.

console.log shows these by name: a file as Coin.png (image), a script as Enemy (script) {…} with its values, a behavior or component the same way.

Behaviors and components as live objects​

entity.behavior('car') and entity.component('light') give the behavior or component itself. Every setting the Inspector shows is a property you can read and write, and it takes effect while the game runs:

const car = entity.behavior('car');
car.grip = 0.3; // ice: the wheels follow at once
car.speed = 25; // a new top speed
if (car.isOnGround) { /* … */ } // behaviors add their own readings…
entity.behavior('platformer').jump(); // …and methods
other.behavior('health')?.damage(1, entity);

entity.behavior('follow').enabled = false; // switch a behavior off and on
entity.component('light').intensity = 2;
entity.component('rigidbody').mass = 5;
  • Both give null when the object has no such behavior or component, so ?. is useful on other objects.
  • What each behavior adds (a Car's speed and steerAngle, a Platformer's jump(), a Health's damage()…) is listed in the editor's completion and under Behaviors in scripts.
  • A few component settings are structural: another shape, another model, a different collider. Those need the object built again; entity.component('mesh').set({ shape: 'sphere' }) sets several at once and rebuilds for you, and entity.rebuild() does it by hand.
  • entity.addBehavior('rotate', { speedY: 180 }), removeBehavior('rotate'), addComponent(…) and removeComponent(…) add and remove them while playing.

getComponent() is the older, read-only way: it gives a copy of the settings, so changing it does nothing.

const maxHp = other.getComponent('health')?.maxHealth;
if (other.hasComponent('car')) { /* … */ }

three.js (advanced)​

The engine draws everything with three.js, and scripts can use it directly when the built-in components are not enough: custom materials and shaders, generated meshes, extra lights, instancing.

  • THREE is the three.js library, in every script. (import * as THREE from 'three' also works, so code from three.js examples can be pasted as it is.)
  • entity.object3d is the three.js object of an object.
  • game.three has the renderer, the current scene and the camera drawing this frame.
// Game script: a glowing ring that pulses, built with three.js
let ring;
function start() {
ring = new THREE.Mesh(
new THREE.TorusGeometry(3, 0.15, 12, 64),
new THREE.MeshStandardMaterial({ color: '#4fc3ff', emissive: '#1a6fff', emissiveIntensity: 2 }),
);
ring.rotation.x = Math.PI / 2;
ring.position.set(0, 0.2, 0);
game.three.scene.add(ring);
}
function update(dt) {
ring.scale.setScalar(1 + Math.sin(game.time * 3) * 0.1);
}
// Object script: give this object a custom shader material
function start() {
const mat = new THREE.ShaderMaterial({
uniforms: { time: { value: 0 } },
vertexShader: 'varying vec3 vPos; void main() { vPos = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
fragmentShader: 'uniform float time; varying vec3 vPos; void main() { gl_FragColor = vec4(0.5 + 0.5 * sin(vPos.y * 4.0 + time * 3.0), 0.3, 0.8, 1.0); }',
});
entity.object3d.traverse((o) => { if (o.isMesh) o.material = mat; });
this.mat = mat;
}
function update(dt) { this.mat.uniforms.time.value += dt; }

Objects you add yourself are not part of the scene in the editor: they exist only while the game runs, they have no physics, and events don't see them. Remove what you add when you no longer need it. The engine still owns the renderer and camera; changing their settings can affect how the game looks everywhere.

Units and conventions​

  • Distances in meters; +Y is up; an object’s forward is βˆ’Z.
  • Angles in degrees (entity.rotation.y = 90).
  • Multiply speeds by dt so the game runs the same on slow and fast phones.
  • Colors are CSS hex strings: "#ff8800".

Examples​

Move with the joystick​

export let speed = 5; // set per object in the Inspector

function update(dt) {
entity.translate(input.axis.x * speed * dt, 0, -input.axis.y * speed * dt);
if (input.axis.x || input.axis.y) {
entity.rotation.y = Math.atan2(-input.axis.x, input.axis.y) * 180 / Math.PI;
}
}

Jump (needs a Physics body and a Collider)​

function update(dt) {
if (input.wasPressed('jump') && entity.isOnGround()) {
const v = entity.getVelocity();
entity.setVelocity(v.x, 7, v.z);
}
}

Collect coins​

function onCollision(other) {
if (other.hasTag('coin')) {
other.destroy();
game.setVar('Score', Number(game.getVar('Score') ?? 0) + 1);
audio.play('Coin');
}
}

Enemy follows the player​

function update(dt) {
const player = game.find('Player');
if (!player) return;
const p = player.getWorldPosition();
entity.lookAt(p.x, entity.position.y, p.z);
if (entity.distanceTo(player) > 1.5) entity.moveToward(p.x, entity.position.y, p.z, 2 * dt);
}

Spawner (game script)​

let timer = 0;
function update(dt) {
timer += dt;
if (timer >= 1) {
timer = 0;
game.spawn('Coin', { x: random(-5, 5), y: 6, z: random(-5, 5) });
}
}

Tap to change color​

const colors = ['#ff5c6c', '#ffb547', '#3ecf8e', '#4f8cff'];
let i = 0;
function onTap() {
i = (i + 1) % colors.length;
entity.setColor(colors[i]);
}

Walk to points (Move to position)​

entity.moveTo(x, z, speed?) walks to a point on the ground, going around walls; onArrived() runs when it gets there. Give the object a Physics body (dynamic, Fixed rotation on) and a Collider so it walks up and down terrain. Without a body it moves in a flat line at its own height.

// A guard walks around a square, forever
const points = [[0, 0], [8, 0], [8, 8], [0, 8]];
let i = 0;

function start() {
entity.moveTo(points[0][0], points[0][1], 3);
}

function onArrived() {
i = (i + 1) % points.length;
entity.moveTo(points[i][0], points[i][1], 3);
}

Tap to move: const p = game.touchWorld(); entity.moveTo(p.x, p.z); inside if (input.tapped) in update. entity.stopMoving() cancels, and entity.movingTo is true while it walks.

A model plays its walk clip while it walks (sprint above speed 6, if it has one) and idle when it stops. Change that with options as the 4th argument:

entity.moveTo(x, z, 8, { sprintSpeed: 10 }); // walk up to 10, sprint above
entity.moveTo(x, z, 3, { animate: false }); // leave the animation alone (play your own)
entity.moveTo(x, z, 3, { avoidWalls: false }); // straight line

UI: pause button​

// Object script on the PauseButton
function onClick() {
game.find('PauseScreen').visible = true;
game.pause();
}
// On a HealthBar (a slider)
entity.setUIValue(entity.getUIValue() - 10);
entity.setText('HP');
entity.setUIColors({ background: '#222', text: '#fff', fill: '#ff5c6c' });
entity.setUIFont('Kenney Pixel'); // a font in Files, by name ('' = the default font)