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β
| Kind | Where it runs | Create it |
|---|---|---|
| π Object script | On 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 script | Once for the whole scene. | Logic β Code scripts β + New β Game script |
| π Library | Nowhere on its own: other scripts import what it exports. See Share code with libraries. | Logic β Code scripts β + New β Library |
| π Editor script | Only in the editor: your own menu commands, Inspector buttons and gizmos. Never in the game. See Editor scripts. | Logic β Code scripts β + New β Editor 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.




- Autocomplete knows the real types: after
entity.behavior('car').it lists the Car's settings and readings, afterentity.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
awaitare 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.
| Function | When | Object | Game |
|---|---|---|---|
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. afterandeveryreturn a function that cancels them.- In a game script or a library,
game.after(seconds, fn, owner?)andgame.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β
| Name | What it is |
|---|---|
entity | The object this script is on (object scripts). Also the type of other in collisions and of results from game.find(). |
game | The running game: find/spawn/destroy objects, variables, scenes, camera, raycasts, saving, data tables (game.table('Item')). |
input | Joystick (input.axis), buttons (input.isDown('jump')), touches, swipes, keys. |
audio | audio.play('Coin'), audio.stop(). |
vars | A storage object for the script. |
field | The kinds of field: export let target = field.object(), field.image(), field.list(β¦)β¦ |
| helpers | lerp, clamp, random, randomInt, deg2rad and JavaScriptβs Math. |
| timers | wait(seconds), after(seconds, fn), every(seconds, fn). See Timers. |
console | console.log() writes to the Debug console. See Print while testing. |
THREE | The three.js library, for advanced effects. See three.js. |
import | Code 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();
| Step | Gives |
|---|---|
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'(orimport Combat from 'Combat') gives the whole library, used asCombat.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,THREEand the helpers, like a game script; there is noentity, 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').hpis always the current value. - You can change them too:
getScript('Enemy').hp = 5changes the Enemy script'shp, asGetComponent<Enemy>().hp = 5would in Unity. An exportedconstcan'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()givesnullwhen the object has no script of that name (upper/lower case doesn't matter). It works onentitytoo, to reach another script on the same object.- Only what is exported can be used;
start,updateand 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
nullwhen the object has no such behavior or component, so?.is useful on other objects. - What each behavior adds (a Car's
speedandsteerAngle, a Platformer'sjump(), a Health'sdamage()β¦) 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, andentity.rebuild()does it by hand. entity.addBehavior('rotate', { speedY: 180 }),removeBehavior('rotate'),addComponent(β¦)andremoveComponent(β¦)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.
THREEis 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.object3dis the three.js object of an object.game.threehas therenderer, the currentsceneand thecameradrawing 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
dtso 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)