Skip to content

Modules

Updated

Scripts do not share variables by default: each Behavior runs in its own scope, so a let score in one script is invisible to every other. That isolation keeps scripts from breaking each other, but a world often needs common data and code: game rules read by many objects, a score several scripts add to, a library downloaded once. This page covers the two ways scripts share with each other: #pragma export and #pragma import between scripts, and named shared instances with Singleton. A library downloaded from a URL with #pragma import(Name="url") has its own page: Dynamic imports.

You want Use
One script to publish a value or an API that others read #pragma export and #pragma import(name)
A JavaScript library from a CDN #pragma import(Name="url")
One shared object, created by whichever script needs it first Singleton
Messages between scripts, without shared state Signals: emit, on, once, off. See Events and signals.

#pragma export(name) publishes one of the script’s variables under its name. #pragma import(name) binds that published value in another script, as a variable of the same name:

GameRules.jx
const rules = { gravity: 9.8, lives: 3 };
const state = { score: 0 };
#pragma export(rules, state)
Player.jx
#pragma import(rules, state)
#pragma lifecycle(startup)
function startup() {
log('lives:', rules.lives);
state.score += 10;
}
  • A pragma may list several names. The exported names must be variables the script declares.
  • The export is published when the exporting script has loaded, after its top-level code ran.
  • The import is bound when the importing script loads, before its top-level code runs. So the exporter must load first: put it earlier in the scene, so the scene creates it first. A Behavior’s executionIndex orders the frame’s hooks, not loading.
  • Mistakes fail the script with a message naming the fix, never a silent undefined:
    • Two scripts exporting one name. Each name has one exporter at a time; rename one of them.
    • Importing a name nobody exported. Check the spelling, and that the exporter loads first.
  • Exporting a name that is also a #define is an error.

An import is a value taken when the importer loads. A number or a string is copied: score++ in the exporter is not seen by importers. To share state that changes, export an object and change its properties, as state.score above, or use a Singleton.

An export lasts as long as its script. When the exporting script stops (its entity destroyed or its scene unloaded) the name is freed. A script loaded again exports it again, and importers that load after that get the new value. Importers that loaded before keep the object they were given.

No script can overwrite, delete or clear what others share: the shared names are not a global any script can reach.

Singleton holds named shared instances for the application: one game manager, one score board, one pool. The first script to ask for a name creates the instance, and every other script gets the same object:

Points.jx
#pragma lifecycle(startup)
function startup() {
const score = Singleton.get('score', () => ({ points: 0, best: 0 }));
score.points += 10;
log('points:', Singleton.score.points);
}
Call What it does
Singleton.get(key, factory) The instance under key. The first call runs factory() to create it; later calls return it and never run a factory again.
Singleton.get(key) The instance, or undefined when there is none.
Singleton.key The instance under key, read-only. Assigning to it throws.
Singleton.has(key) Whether an instance exists under key.
Singleton.delete(key) Remove the instance, calling its dispose() when it has one. Returns whether there was one.
  • Unlike an export, a singleton does not depend on load order: whichever script runs first creates it.
  • The key is a non-empty string, and cannot be get, has or delete.
  • Only the script that created an instance can delete it while that script runs. Once the creator has stopped, any script may.
  • Instances stay when the script that created them stops, and across scene switches, for the life of the application.
  • A factory that asks for its own key while creating it throws.

One script publishes the settings; any number of scripts read them.

Settings.jx
// Put this Behavior entity near the top of the scene, so it loads first.
const settings = {
enemySpeed: 2.5,
pickupValue: 10,
difficulty: 'normal',
};
#pragma export(settings)
Enemy.jx
#pragma import(settings)
#pragma lifecycle(update)
function update(dt) {
self.parent.position.z += settings.enemySpeed * dt;
}

How it works:

  • #pragma export(settings) publishes the object once Settings.jx has run its top-level code.
  • #pragma import(settings) binds the same object in Enemy.jx before its own top-level code runs.
  • Because the exporter must load first, its Behavior entity sits earlier in the scene than the importers.

An export can be an object of functions, so other scripts call into it instead of touching its data.

Scoreboard.jx
#pragma lifecycle(startup)
let total = 0;
let label = null;
const scoreboard = {
add(points) {
total += points;
if (label) label.setProps({ text: `Score: ${total}` });
},
get total() {
return total;
},
};
#pragma export(scoreboard)
function startup() {
label = findEntity('Score Label')?.getComponent(UILabelComponent);
scoreboard.add(0);
}
Pickup.jx
#pragma import(scoreboard)
#pragma lifecycle(startup)
function startup() {
on('pickup/clicked', (event) => {
if (event.eventType !== EventType.Selectable.Select) return;
findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again
scoreboard.add(5);
log('Score is now', scoreboard.total);
});
}

How it works:

  • scoreboard closes over total and label, which stay private to Scoreboard.jx.
  • get total() is a getter: importers read scoreboard.total and always see the current value, unlike an exported number, which would be copied once.
  • Pickup.jx assumes its parent has a Selectable and a Signal Emitter on pickup/clicked.

A singleton needs no load order: every level script asks for the same manager, and the first one creates it.

Level.jx
#pragma lifecycle(startup)
function createGame() {
const game = { level: 1, coins: 0 };
game.addCoin = () => {
game.coins += 1;
emit('game/coins', { coins: game.coins });
};
return game;
}
function startup() {
const game = Singleton.get('game', createGame);
log('Level', game.level, '- coins so far:', game.coins);
on('coin/collected', () => game.addCoin());
on('level/complete', () => {
game.level += 1;
Scenes.load('level-' + game.level);
});
}

How it works:

  • Singleton.get('game', createGame) runs createGame only the first time; every later call, from any script, returns the same object.
  • The instance survives scene switches, so the coin count carries over from level to level while each level’s own scripts start fresh.
  • addCoin refers to the object by its name, game, rather than through this: arrow functions keep the code clear, and in a script the Behavior’s entity is always self, never this.

The importer fails with a message saying no script exported the name. Move the exporting Behavior entity earlier in the scene, or share through a Singleton, which does not depend on load order.

Exporting a number and expecting it to update

Section titled “Exporting a number and expecting it to update”
Wrong
let score = 0;
#pragma export(score)
on('coin', () => { score += 1; }); // importers keep the 0 they were given
Right
const score = { value: 0 };
#pragma export(score)
on('coin', () => { score.value += 1; }); // importers read score.value

Each name has one exporter at a time; the second script fails to start. Give each export a distinct name, such as levelRules and shopRules.

Wrong
Singleton.score = { points: 0 }; // throws: read-only
Right
const score = Singleton.get('score', () => ({ points: 0 }));
score.points += 1;