Objects and handles
An object is one instance of an object type in the world: the crate by the door, the
player, one coin. Objects exist only at runtime. They are created by a level (placed
objects), by code (spawnObject), or as parts of another object.
Handles
Gameplay never holds a pointer to an object. It holds a handle: a small value made of an index and a generation number.
- Destroying an object bumps the generation, so old handles resolve to
nullinstead of pointing at something else. - Handles are plain values. Copy them, store them in components, keep them across frames and across code reloads.
Handle<Object>can point at any object.Handle<Player>points at aPlayer.
const handle = spawnObject("Player", spawnPosition(0)); // Handle<Object>
const typed = handle.as<Player>(); // Handle<Player> | null
const player = typed?.get(); // Player | null
if (player) player.transform.position.y += 1;
| Expression | Type | Meaning |
|---|---|---|
h.get() |
Object | null |
The live object, or null if destroyed. Object has only .handle and .destroy() |
h.as<T>() |
Handle<T> | null |
null unless h is live and of exactly type T |
h.as<T>()?.get() |
T | null |
The usual way to get at an object's components |
obj.handle |
Handle<Object> |
The handle of an object you have |
h == other |
bool |
Same object (index and generation) |
A handle is not a condition: if (h) is an error
(a condition must be bool or a number, got Handle<Object>). Test h.get() instead.
There is no literal for a null handle. Component fields of handle type start null, and
placedObject("") returns a null handle (Gridline uses it as "no object").
Finding objects
| Call | Returns |
|---|---|
placedObject("id") |
The object the current level placed with that id, or a null handle |
spawnObject("Type", position) |
A new object of that type |
obj.handle inside a behavior |
The current object |
a part field, owner.camera |
The part's handle, nullable |
physicsRaycast(...), contacts |
hit.object, contact.first, contact.second |
There is no "find all objects of a type" call. Use a behavior over a component that type
has, or keep your own list of handles (Gridline keeps an Array<Handle<Object>> in game
memory).
Creating and destroying
spawnObject(type, position)creates the object at once (you can read and write its components right away), but it first appears in behavior queries on the next tick.obj.destroy()is deferred to the end of the tick: the object stays valid until then, and its handles returnnullfrom the next tick on. Its parts are destroyed with it.- Objects placed by a level, or spawned while a level is loaded, belong to that level and are destroyed when it unloads. Objects spawned with no level loaded live until destroyed.
Handles are local
A handle means something only inside one running game. Matching objects across machines needs network ids, which come with networking later.