Entities: setOwner() method
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe setOwner() method of the Entities interface gives an entity to a player, or back to the room. The owner may write the fields its kind declares writable from its client.
Syntax
setOwner(entity, owner)
Parameters
entity- The
RoomEntityto give. owner- The player ID of the new owner, a non-empty string of at most
MAX_PLAYER_ID(256) characters, orundefinedto give the entity back to the room.
Return value
None (undefined).
Exceptions
Error- Thrown if
entityisn’t a live entity of the room’sentities, such as one already deleted, orroom.state; or if its kind is hidden andownerisn’tundefined. TypeError- Thrown if
entityisn’t an entity object, or ifownerisn’t a valid player ID.
Description
Owners are player IDs, not connections, and the player doesn’t need to be connected. Ownership is room state, so it survives reconnects and hibernation. Giving an entity to the player who already owns it does nothing.
The new owner gets the kind’s ownerOnly fields right after the change, and the entity is always in its view. The previous owner’s writes no longer apply, and it keeps the ownerOnly values it had. The room may still write any field of an entity a player owns.
When the owner’s presence ends, the kind’s onOwnerLeave decides what happens to what the player still owns; see When the owner leaves.
Examples
Passing the ball to a teammate
// pass.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";
const Ball = entity("ball", { x: "f32", y: "f32" }, { writable: ["x", "y"] });
export default defineRoom({
schema: defineSchema({ state: entity("match", { ball: "u32" }), entities: [Ball] }),
onCreate(room) {
room.state.ball = room.entities.create(Ball).id;
},
onMessage(room, connection, message) {
const to = (message as { passTo?: unknown } | null)?.passTo;
const ball = room.entities.get(room.state.ball);
if (typeof to !== "string" || !ball || room.entities.ownerOf(ball) !== connection.player) return;
if (room.presence.get(to)?.connected) room.entities.setOwner(ball, to);
},
});
See also
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
setOwner() | 0.1 | 0.1 | 0.1 | 0.1 |