Scene scripts, variables, and storage
Coordinate a level with scene APIs, runtime objects, scene variables, audio, and storage with three save slots that follows a signed-in player across devices.
Scene scripts
Assign one project script in Scene Settings. It receives the same init, update, and destroy lifecycle but runs once for the scene rather than once per object.
Every object and scene script can call scene.loadScene(idOrName), scene.restart(), scene.pauseGame(), and scene.resumeGame(). Restart reloads the current authored scene in Preview or published play and returns false in editor Play, where no scene loader exists. Pause freezes physics, per-frame updates, and gameplay audio while leaving GUI rendering and onClick active; resume continues the same run. After a restart or scene change the new scene's init() runs once every object is in place, characters still loading their models included, so scene.getObjectByName finds them there.
scene.getStartReason() says why the current run started, and every object and scene script can call it: "load" for a page load of the game or Preview (and editor Play), "restart" for the player's Restart button, scene.restart(), or scene.loadScene of the scene already playing, and "scene_change" after scene.loadScene moved to a different scene. It is the same for every script in the run. In a multiplayer room the room server and each player's browser report their own start by the same rule; a player who joins mid-game sees "load".
In a multiplayer room the scene script runs on the room server, not in any player's browser. Only the scene script may call scene.loadScene and scene.restart there (publication refuses either call in an object's script), and every player moves with the room. Nothing carries over unless the optional second table names it: scene.loadScene("Arena", { keep = { game = { "round" } } }) keeps the round key of game state, and keep may also list participant, avatar and private keys. scene.restart({ keep = ... }) takes the same table. Only the scene script and other authority scripts may call pauseGame and resumeGame; a GUI button cannot. See Build and test a multiplayer game.
Lookup and physics
Scene scripts can call scene.getObjectByName(name), scene.getObjectsByNamePrefix(prefix), scene.getObject(id), scene.getObjectsByType(type), scene.getObjectsByTag(tag), scene.getGravity(), scene.setGravity(x,y,z), and scene.log(message). These are not on an object script's scene — there scene.getObjectByName is nil. Object scripts make the same five lookups through gameObject instead (gameObject.getObjectByName(name) and so on); gravity is scene-script-only. In a multiplayer room only the scene script, on the room server, may call setGravity.
Look up only what the script uses. Resolve each object once in init() and keep it, rather than every frame. In Preview and published games, unscripted static cubes, spheres, cylinders and capsules that look alike are drawn together in batches, and any object a script is handed leaves its batch and is drawn on its own for the rest of the play. So a scene script that collects the scenery with scene.getObjectsByType("cube"), or a prefix most of the scene shares, takes all of it out of its batches and can cost a large scene most of that saving. Give the objects the script needs names of their own and look those up. See "Performance: point light budget and render scale" in Editor basics.
scene.findPath(from, to) and scene.getNearestNavPoint(point) query the navigation mesh from arbitrary world-space points. They are available to object scripts too and return nil until the bake completes or when no reachable answer exists.
Authored waypoint paths
scene.getWaypointPath(idOrName) is available to both scene and object scripts. It returns {id, name, points}, or nil when the path is missing. Each point has a stable id, a world-space position = {x, y, z}, and optional label, waitSeconds, and eventName. Point order is the authored order. Coordinates include the path's complete parent transform; read the path again if that transform changes.
To make an actor traverse the route, call its followWaypointPath(idOrName, traversal?). It routes each leg over the navmesh and supports waits and named arrival events on the moving object's own script. See Authored waypoint patrols. scene.findPath(from, to) returns nil for an unreachable destination, including a partial Recast corridor, as well as while the mesh is not ready. A first nil while baking is not evidence that a destination is unreachable.
Time scale and slow motion
scene.setTimeScale(scale) sets how many game seconds pass per real second: 0.5 is half speed, 2 double. It is a scene-script call. The scale is clamped to 0 to 4, and the call returns the scale it applied; a NaN or nil scale is refused and reported, and the scale stays where it was. Every script can read it with scene.getTimeScale(). It goes back to 1 when the game stops and at every start.
Game time drives the physics, the deltaTime every object, GUI and scene script's update receives, animation, characters, vehicles, buoyancy, navigation agents, shader time, trails and particles, so a script that moves things by deltaTime slows down with no change. Real time drives the built-in first- and third-person cameras, held-stick look, the editor's fly camera and audio, whose pitch and volume ramps are not scaled. scene.getUnscaledDeltaTime() is the real seconds of the current step (one step per frame at 30 fps or better; see "Slow frames" below), for a scripted camera, GUI or timer that must keep its real pace through slow motion. scene.getTime() is game seconds since the run started and scene.getUnscaledTime() real seconds.
A scale of 0 freezes the world: nothing moves, but every update still runs with deltaTime 0, so the script that froze it can start it again. scene.pauseGame() is different, because it stops the updates as well. In a multiplayer room setTimeScale raises an error, because every player shares the room's simulation; see Build and test a multiplayer game.
Slow frames. Each step of the game covers at most 1/30 of a real second (times the time scale). In single player, a displayed frame slower than that, below 30 fps, is split into equal steps of at most 1/30 s each, up to half a second of real time per frame, so the game keeps up with real time down to 2 fps instead of running in slow motion. Every step is a whole one: each script's update, its timers, animation, characters, vehicles and physics run once per step, so update can run several times between two displayed frames. Measure time by adding up deltaTime, never by counting updates. Mouse look and a button's press arrive on the first step of a frame only. Below 2 fps, or when the scripts and physics themselves are what makes frames slow, the game takes fewer steps and runs in slow motion rather than stalling. A multiplayer client still steps once per frame and the room's server at a fixed rate. Before 16 October 2026 a slow frame was always a single step, so a game below 30 fps ran in slow motion.
This scene script eases into 30% speed, holds it for two real seconds and eases back out when any script sets the slowMotion scene variable:
local SLOW, EASE, HOLD = 0.3, 0.25, 2.0 -- scale, then real seconds
local elapsed = nil
local function lerp(a, b, t)
return a + (b - a) * math.max(0, math.min(1, t))
end
function update(deltaTime)
if scene.getVar("slowMotion") == true then
scene.setVar("slowMotion", false)
elapsed = 0
end
if elapsed == nil then return end
elapsed = elapsed + scene.getUnscaledDeltaTime()
local scale
if elapsed < EASE then
scale = lerp(1, SLOW, elapsed / EASE)
elseif elapsed < EASE + HOLD then
scale = SLOW
else
scale = lerp(SLOW, 1, (elapsed - EASE - HOLD) / EASE)
end
scene.setTimeScale(scale)
if scale >= 1 and elapsed > EASE then elapsed = nil end
end
Timers
Object and scene scripts have a timer global for delays and repeats on game time: timer.after(seconds, callback) runs once, timer.every(seconds, callback) repeats, both return a handle with handle:cancel(), and timer.cancelAll() clears the script's timers. They follow scene.setTimeScale and stop while the game is paused, fire before update in the step they fall due, skip repeats a slow frame missed rather than catching up, and are cleared by Stop and by a scene change, so schedule them in init(). At most 256 may be live in one script. See Simulation-time timers for the full rules.
timer.after(2, function() scene.setVar("doorsOpen", true) end)
local pulse = timer.every(1, function() scene.setVar("tick", (scene.getVar("tick") or 0) + 1) end)
-- later
pulse:cancel()
Radial gravity
Scene scripts can pull everything toward a point for the rest of the run. Call it once from init:
function init()
scene.setRadialGravity({
center = { x = 0, y = 0, z = 0 },
strength = 9.81,
falloff = "none", -- or "inverseSquare"
radius = 20, -- where strength applies, for inverseSquare
maxDistance = 80, -- the scene's own gravity beyond this (nil = everywhere)
alignCharacters = true, -- characters stand up away from the centre
})
end
scene.clearRadialGravity() removes it, scene.getRadialGravity() returns its settings or nil, and scene.getGravityAt(x, y, z) returns the gravity at a point. A table it cannot use raises an error naming the field. There is one source per scene; for several planets, switch it as the player moves between them. It raises an error in a multiplayer room, publishing a multiplayer game that calls it shows a warning, and Stop clears it.
Cameras
scene.setActiveCamera(id) selects which authored camera renders the running scene and returns true. Pass the camera object's UUID, not its name; it returns false if the ID does not resolve to a camera in the running scene. The change is runtime-only — it does not alter the authored isActive setting you see when the scene is next opened in the editor. scene.getActiveCamera() returns the object API for whichever camera is currently active, or nil if none is. Both are available to object scripts as well as scene scripts. In a multiplayer room the camera belongs to each player's browser, so call them from a camera or GUI script there; the scene script and characters' control scripts cannot.
-- Hand control to a second character's camera mid-game.
scene.setActiveCamera("b4c74f8a-c2c9-4e03-9a83-6ea8036bba7a")
-- Read the live transform of whatever is rendering now.
local camera = scene.getActiveCamera()
if camera then
local forward = camera.getForward()
end
gameObject.setVisible() does not change which camera renders. On a camera it hides only what is parented to the camera, such as a first-person viewmodel. Use scene.setActiveCamera() to switch cameras.
Scene variables
scene.getVar(name) reads number, string, boolean, or object-reference values. scene.setVar(name,value) updates primitive values for the running scene.
Scene variables stay on one browser
They are not replicated. Every browser in a multiplayer room keeps its own copy, so a value the scene script writes with scene.setVar — on the room server — never reaches any player, whatever the variable is named. Share state between players with the multiplayer state partitions instead; see Build and test a multiplayer game.
Finding objects by tag
scene.getObjectsByTag("pickup") returns live object APIs in the current scene, in scene order, or an empty list. Object scripts use gameObject.getObjectsByTag("pickup") instead. Author tags in the inspector: up to 16 unique lowercase labels, each 1–32 characters, starting with a letter and using letters, digits, underscores or hyphens. Matching is exact and case sensitive.
Runtime objects
Creation options may include tags = { "pickup", "quest_item" }. Invalid lists refuse creation. Runtime clones inherit the source object's tags. Read them through object.getTags() or test one with object.hasTag("pickup"); there is no runtime tag mutator. Queries follow creation, deferred removal and scene changes.
scene.createObject(type, options) creates a simulation-only object and returns its object API. type is one of cube, sphere, cylinder, capsule, heightField, water, camera, empty, ambientLight, directionalLight, pointLight, hemisphereLight, particleEmitter, guiLabel, guiPanel, guiImage, guiButton, guiSlider, guiProgressBar, mesh, or character. A guiSlider is created with the default 0-1 range; call setRange and setValue on the returned object. A guiProgressBar takes its authored fields as options — value (0–1), fillColor, backgroundColor, fillDirection, width, height, borderRadius, opacity, ariaLabel and the shared anchor and layout fields — and a value that is not a finite number returns nil. options is optional and accepts name, position, rotation (a quaternion {x=, y=, z=, w=}), scale, motion ("static"|"dynamic"|"kinematic"|"rig"), materialId, plus shape-specific fields: extent (cube and water), radius (sphere, cylinder, capsule), halfHeight (cylinder, capsule), buoyancy, linearDrag, angularDrag, fluidVelocity (water), and any particle emitter setting by its field name, such as emissionRate, burstCount or colorStart (particleEmitter). Two booleans match the authored fields: visible = false on a cube, sphere, cylinder, capsule or mesh makes an invisible collider, which is not drawn, casts no shadow and still collides, and castsShadow = false on those types or a character turns its shadow off. Both default to true, and other types ignore them. Anything you leave out takes the type's default — including motion, which is "static" for the primitive shapes, so pass motion = "dynamic" for something that should fall or be pushed. A primitive created with motion = "rig" has no collider at all, which suits pooled effects such as sparks and shells. An unknown type returns nil, and so does a visible or castsShadow that is not a boolean (visible = 0 is true in Lua), with a warning. createObject is a scene-script call; object scripts do not have it. A runtime object created this way is not saved to the scene file. In a multiplayer room only authority scripts may create or destroy objects, and an object created at runtime is not shared with players; copy a spawn template with multiplayer.spawn for one every player sees.
-- Invisible barriers down both sides of a straight
for i = 0, 9 do
for _, x in ipairs({ -8, 8 }) do
scene.createObject("cube", {
name = "Barrier",
position = { x = x, y = 1, z = i * 10 },
extent = { x = 0.5, y = 2, z = 10 },
visible = false,
})
end
end
-- A one-off explosion: a burst of 80 particles and no steady emission
local function explode(position)
scene.createObject("particleEmitter", {
position = position,
emissionRate = 0,
burstCount = 80,
maxParticles = 80,
lifetimeMin = 0.4,
lifetimeMax = 1.2,
speedMin = 4,
speedMax = 10,
spreadAngle = 180,
drag = 2,
sizeStart = 0.6,
sizeEnd = 2,
colorStart = { r = 1, g = 0.8, b = 0.3 },
colorEnd = { r = 0.4, g = 0.1, b = 0 },
blending = "additive",
})
end
A runtime particle emitter fires its burstCount as soon as it is created, if it is emitting. In a multiplayer room the room server draws no particles, so an emitter a scene script creates there is never seen; author the emitter in the scene and have its own script call emit(count) instead.
scene.cloneObject(source, options) copies an existing object and everything under it (children, a panel's GUI contents, variables, materials and scripts) as runtime objects, and returns the copy's object API, or nil when source names nothing or the game is not running. source is an object's API, its id or its name. options is optional and takes the same name, position, rotation and scale as createObject, applied to the copy's root. The root keeps the source's parent, so these are in the same frame as the source's transform: world space for a top-level object. A top-level source copied without a position or rotation is placed where it is now, and the copy keeps the source's name unless you give one. Every copy gets new ids, and an object_ref variable, camera target, constraint body or path source that points inside the copied group points at the copy's own object; one that points outside it still names the original. Variables are copied as they stand at the call. A scripted copy gets its own script, which runs its own init(). Like createObject, it is a scene-script call, copies are never saved, and they are removed when the game stops. In a multiplayer room only authority scripts may call it, and the copy exists only on the room server; use multiplayer.spawn for copies every player sees.
-- One "Crate Stack" group built in the editor, copied into a row.
for i = 1, 5 do
scene.cloneObject("Crate Stack", { position = { x = i * 3, y = 2, z = 10 } })
end
scene.destroyObject(id) and scene.destroyObjectByRef(object) remove any scene object — authored or runtime-created — for the rest of the current simulation; authored objects return automatically when simulation stops. See Cross-object interactions for the full destroy API, including the per-object destroy() method available on any resolved object API.
Audio and scene transitions
The audio calls on scene are on every script's scene, object scripts included. Use scene.playSound(assetId, options) for one-shot effects that are not tied to a place in the world — UI blips, stingers — and stop or check them with scene.stopSound(soundId, fadeOutSeconds?) and scene.isSoundPlaying(soundId), using the id playSound returned. scene.setSoundVolume(soundId, volume, rampSeconds?) and scene.setSoundPlaybackRate(soundId, rate, rampSeconds?) change one while it plays, ramping to the new value; see Lua object API for their ranges. options accepts volume, loop, playbackRate, and fadeIn. scene.stopAllSounds(fadeOutSeconds?) stops every active effect at once (music is untouched). For background music, use scene.playMusic(assetId, options) (volume, loop, fadeIn, and crossfade seconds of overlap with the current track), scene.stopMusic, scene.setMusicVolume, and scene.setSfxVolume. For a sound that comes from an object, call gameObject.playSound from that object's script instead; it plays positionally at the object, and scene.stopSound can stop it too.
Filters and reverb
A filter table is {type="lowpass"|"highpass"|"bandpass", frequency=hertz, q=number}: type defaults to lowpass, frequency to 1000 (clamped to 10–22050) and q to 1 (clamped to 0.0001–30). A lowpass or highpass sweeps in from fully open, and back out, over the ramp. scene.playSound takes one as its filter option, and scene.setSoundFilter(soundId, filter, rampSeconds?) puts one on a playing sound or takes it off with nil, with the same id rules as setSoundVolume.
scene.setSfxFilter(filter, rampSeconds?) and scene.setMusicFilter(filter, rampSeconds?) filter the whole sound-effects or music mix, for a muffle under water or behind a pause menu. The effects filter covers positional sounds and the reverb's tail too. nil removes it, a table that is not a filter returns false, and both are cleared at every start and at Stop.
scene.setReverb(preset, wet?, rampSeconds?) changes the scene's reverb for the rest of the run. preset is "none", "room", "hall", "tunnel", "stadium" or "cave"; wet is the mix from 0 to 1, clamped, and leaving it out keeps the current mix. A preset change crossfades over the ramp. It returns false for an unknown preset or a non-finite mix, and Stop puts back the reverb from Scene Settings, where music is left dry unless Reverb on music is on.
-- On a trigger volume at a tunnel mouth
function init()
gameObject.registerForCollisions()
end
function onTriggerEnter(other)
scene.setReverb("tunnel", 0.4, 0.5)
end
function onTriggerExit(other)
scene.setReverb("none", nil, 0.5)
end
-- Under water: muffle every effect, and lift it again on surfacing
scene.setSfxFilter({ frequency = 500 }, 0.3)
scene.setSfxFilter(nil, 0.3)
-- A radio voice: a narrow band around 1500 Hz
scene.playSound(radioVoiceAssetId, { filter = { type = "bandpass", frequency = 1500, q = 2 } })
Filters and reverb are presentation calls: in a multiplayer room make them from a camera, GUI or presentation script, which runs in each player's browser. A presentation object has no collider, so there the tunnel check belongs in a camera script that tests where the camera is, not in a trigger.
In a multiplayer room the scene script runs on the room server, which has no speakers, so these calls are refused there. Play a room's music and non-positional sound from a camera, GUI, or presentation script's scene instead, or positional sound with its gameObject.playSound; those scripts run in each player's browser. A scene's Music setting plays in a room without any script. scene.loadScene(idOrName) queues a transition to another included scene and returns ok, reason: false, "unknown_scene" when no included scene has that id or name, false, "unsupported" in editor Play, and in a room "not_scene_script", "not_authority", "transition_pending", "rate_limited" or "invalid_keep" (a keep table naming something other than the four partitions); use scene.restart() when the destination is the current scene so renaming it cannot break the script.
Menu scenes and player actions
Choose a menu scene in the project page's Game startup section, which also sets the Solo start scene, an optional separate Multiplayer start scene for rooms (by default the same as the solo one), and whether a multiplayer game may be played without a room (Solo play). The menu must have an active camera and differ from both start scenes, and rooms never load it. Preview opens the menu when you preview either the menu or the solo start scene; previewing another scene, the multiplayer start scene included, opens that scene directly. Menu scripts start automatically, GUI buttons are interactive, and gameplay movement and pointer lock stay inactive.
The player global is available to both object and scene scripts. Attach this script to a GUI button to enter solo play at the solo start scene, using player slot 1:
function onClick()
local ok, reason = player.startSolo()
if not ok then print(reason) end
end
For a multiplayer button, call player.openMultiplayer() instead. It opens the existing app-host multiplayer picker for the selected published release, keeping sign-in, player profiles, lobby choices and room management. It takes no URL or room arguments. Players joining a room bypass the local menu.
Both calls return ok, reason. A refusal returns false with "unsupported" when the engine has no player host (such as editor Run), "not_in_menu" outside a local menu, "busy" during a transition, "solo_unavailable" when a multiplayer game's Solo play setting does not allow play without a room (the menu stays active, so its multiplayer button still works), or "multiplayer_unavailable" when no published picker is available. Local Preview has no published picker, so its multiplayer button returns false, "multiplayer_unavailable". These actions cannot start gameplay or navigate from a multiplayer room.
If your game begins play inside its menu scene without changing scene, call player.markGameplayStarted() once from the handler that starts play. It records the game as started for the creator's analytics, changes nothing on screen, and returns ok, reason with "unsupported" when there is no player host. Ordinary scene changes into gameplay record this themselves, so do not call it on menu load or on settings clicks.
For a real draft room test, see Test in a room. In local solo play, ordinary scene.loadScene(idOrName) can return to the selected menu. Leaving a multiplayer room uses its existing room-exit flow. Republish after changing the menu or startup settings.
Game storage
local highScore = gameStorage.get("highScore") or 0
gameStorage.set("highScore", math.max(highScore, 250))
gameStorage.remove("temporaryValue")
-- gameStorage.clear() removes every value in the slot in use.
Keys are non-empty strings. Values can be numbers, strings, booleans, or tables of those (lists or keyed tables, nested); a function, math.huge, or a table that contains itself raises an error. gameStorage.get returns a copy, so change a stored table by setting it again. Values are shared by every scene of the game.
gameStorage is stored on the player's own device, so reads and writes happen immediately, even offline. In a published single-player game, a signed-in player's storage also syncs to their account and follows them to their other devices. In a multiplayer room only GUI, camera, and presentation scripts may use it. There it never syncs and is never shared between players, so keep anything the room must agree on in multiplayer state.
Saves across devices
Sync needs no script changes. The player handles it, not the game:
- Signed out, the game works exactly as before and saves only on the device. The first time the game saves, a Sign in to save offer appears at the bottom of the screen. Not now is remembered on that device, and Sign in to save progress stays in the menu. A game cannot show, fake, or hide the offer.
- Signing in brings in the account's save before
init()runs. If only one side has changed since they last matched, that side is used. If both have changed, the game pauses and asks the player which save to keep, showing when and on which device the account's save was made. The other save is replaced. Saves are never merged. - While playing, writes reach the device immediately and upload a couple of seconds after the last change, retrying if the network drops. If another device saved in the meantime, the player gets the same question. Choosing the account's save reloads the game with it.
- A save belongs to the published game, not a release, so it survives a republish. If you change what you store, keep a version number inside your data and update older saves in
init(). - A synced save holds at most 64 KB of JSON. A larger save stays on the device only.
- Only the published game's own address syncs. Editor Play, Preview, test links and multiplayer rooms never do.
- Teen accounts follow their guardian's settings. If a guardian allows only approved games, saves sync only in the games that guardian has approved.
- Sign out of saves in the menu stops syncing on that device. Anything already saved on the device stays there.
gameStorage.syncState() returns where the save is:
"local": on this device only, because the player is signed out, offline, or not in a published game."syncing"."synced"."conflict": the player is choosing between two saves.
Use it only for a save indicator. Reads and writes behave the same in every state. It describes the slot in use.
Save slots
A game has three save slots, 0, 1 and 2. Each is a separate save, kept on the device and synced to the account on its own. A game that never chooses a slot keeps everything in slot 0, so existing games need no change.
gameStorage.useSlot(n)switches every othergameStoragecall to slotn. Anything but 0, 1 or 2 raises an error.gameStorage.slot()returns the slot in use.gameStorage.slotInfo(n)returns{ empty = true }for an empty slot, or{ empty = false, savedAt = seconds }, wheresavedAtis when the slot was last saved, in epoch seconds.os.dateformats it.
Every page load starts on slot 0. A chosen slot stays chosen through scene.restart(), the Restart button and scene.loadScene, so pick it once on a save-select screen and let the gameplay scripts use plain get and set. gameStorage.clear() empties only the slot in use. When a signed-in player has two different saves in more than one slot, the game asks about each slot in turn and names the slot it is asking about.
Put this script on three GUI buttons in the menu scene, each with a number variable slot set to 0, 1 or 2:
local slot
function init()
slot = gameObject.getVar("slot")
local info = gameStorage.slotInfo(slot)
local label = "Slot " .. (slot + 1) .. ": "
if info.empty then
gameObject.setText(label .. "New game")
else
gameObject.setText(label .. os.date("%b %d %H:%M", info.savedAt))
end
end
function onClick()
gameStorage.useSlot(slot)
local ok, reason = player.startSolo()
if not ok then print(reason) end
end
The account's saves arrive before init() runs, so a signed-in player sees the dates of saves made on their other devices. To add a delete button, call gameStorage.useSlot(n) and then gameStorage.clear().
gameStorage is not cleared by a restart. The player's Restart button and scene.restart() rebuild the scene from its authored state but leave saved values in place, so a game that resumes a saved checkpoint would undo the restart. Check scene.getStartReason() before resuming:
function init()
if scene.getStartReason() == "restart" then
gameStorage.remove("checkpoint")
end
local checkpoint = gameStorage.get("checkpoint")
if checkpoint then
gameObject.setPosition(checkpoint.x, checkpoint.y, checkpoint.z)
end
end