# Entities: setOwner() method

> The setOwner() method of the Entities interface gives an entity to a player, or back to the room.

The **`setOwner()`** method of the [`Entities`](/docs/room/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

```ts
setOwner(entity, owner)
```

### Parameters

`entity`
: The [`RoomEntity`](/docs/room/room-entity) to give.

`owner`
: The player ID of the new owner, a non-empty string of at most `MAX_PLAYER_ID` (256) characters, or `undefined` to give the entity back to the room.

### Return value

None (`undefined`).

### Exceptions

`Error`
: Thrown if `entity` isn't a live entity of the room's `entities`, such as one already deleted, or `room.state`; or if its kind is hidden and `owner` isn't `undefined`.

`TypeError`
: Thrown if `entity` isn't an entity object, or if `owner` isn'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](/docs/room/guides/ownership#when-the-owner-leaves).

## Examples

### Passing the ball to a teammate

```ts
// 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

- [`Entities.ownerOf()`](/docs/room/entities/ownerof)
- [`Entities.ownedBy()`](/docs/room/entities/ownedby)
- [Ownership](/docs/room/guides/ownership)
