Entities: create() method
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe create() method of the Entities interface creates an entity of a kind and returns it. Clients that see it get it in the next state update.
Syntax
create(kind)
create(kind, values)
create(kind, values, options)
Parameters
kind- The entity’s kind, one of the kinds in the schema’s
entities. valuesOptional- An object with values for any of the kind’s fields. A field left out gets its default; see Defaults.
optionsOptional-
An object with any of these properties:
id- The entity’s ID, an integer from 2 to
MAX_ENTITY_ID(2^32 − 1) that no live entity has. Without it, the entity gets the next automatic ID. owner- The player ID of the player who owns the entity from the start, a non-empty string of at most
MAX_PLAYER_ID(256) characters. Without it, the room owns it.
Return value
The new RoomEntity.
Exceptions
Error- Thrown if
kindisn’t in the room’s schema, or is its shared or private state kind; ifidis taken by a live entity; if the kind is hidden andowneris given; or, for a kind with a key, if the key is missing,"", or taken by a live entity of the kind. The message names the entity that has the ID or key. TypeError- Thrown if
valuesnames a field the kind doesn’t have, if a value has the wrong type, or ifownerisn’t a valid player ID. RangeError- Thrown if
idis out of range or not an integer, if a number is out of its field’s range or a value is over its size limit, or if the entity would be over 61,376 bytes encoded.
Description
Automatic IDs start at 2, since 0 and 1 are the shared and private state, and each is above every ID the room has used, so an automatic ID is never reused. An explicit id lets the room and its clients compute an entity’s ID, such as a chunk’s from its coordinates. An automatic ID created earlier can take an ID you meant to compute, so create entities with computed IDs first, in onCreate. A deleted entity’s ID can be given to a new one with id, even in the same tick.
An entity created and deleted before the next state update sends nothing to clients.
Examples
Building a level’s doors from its file
The doors’ IDs come from the level file, and each door has a key, so the room and its clients can find a door by name.
// level.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";
const Door = entity("door", { name: "string", locked: "bool" }, { key: "name" });
const LEVEL = [
{ id: 100, name: "armory", locked: true },
{ id: 101, name: "hall", locked: false },
];
export default defineRoom({
schema: defineSchema({ entities: [Door] }),
onCreate(room) {
for (const { id, name, locked } of LEVEL) room.entities.create(Door, { name, locked }, { id });
},
});
See also
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
create() | 0.1 | 0.1 | 0.1 | 0.1 |