# Entities

> The Entities interface of the Room API holds a room's entities, and creates, deletes, finds and gives them to players.

The **`Entities`** interface of the [Room API](/docs/room) holds a room's entities: it creates and deletes them, finds them by ID, key or kind, and gives them to players. Each room has one, as [`room.entities`](/docs/room/room/entities).

It's also the world the room's stepper gets, so a stepper reads and writes the same entities as the hooks do.

What it holds:

- Every entity the room created and hasn't deleted, of every kind in the schema's `entities`, hidden kinds included.
- Not `room.state`, private state or [presence](/docs/room/presence) entries. Only [`get()`](/docs/room/entities/get) with ID 0 and [`all()`](/docs/room/entities/all) of the shared state kind give `room.state`, as a stepper's world does on the client too.

Each entity is a [`RoomEntity`](/docs/room/room-entity). Entities are room state: they're saved, restored on wake and kept across a room host crash, with their IDs, keys and owners.

## Instance properties

[`Entities.count`](/docs/room/entities/count)
: The number of entities. Read only.

## Instance methods

[`Entities.create()`](/docs/room/entities/create)
: Creates an entity of a kind and returns it.

[`Entities.delete()`](/docs/room/entities/delete)
: Deletes an entity.

[`Entities.get()`](/docs/room/entities/get)
: Returns the entity with an ID, or the entity of a kind with a key.

[`Entities.all()`](/docs/room/entities/all)
: Returns an iterator over every entity of a kind.

[`Entities.setOwner()`](/docs/room/entities/setowner)
: Gives an entity to a player, or back to the room.

[`Entities.ownerOf()`](/docs/room/entities/ownerof)
: Returns the player who owns an entity, or `undefined` for the room.

[`Entities.ownedBy()`](/docs/room/entities/ownedby)
: Returns an iterator over the entities of a kind a player owns.

## Examples

### Spawning and collecting coins

```ts
// coins.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";

const Coin = entity("coin", { x: "f32", y: "f32", value: "u8" });

export default defineRoom({
  schema: defineSchema({ entities: [Coin] }),
  onCreate(room) {
    for (let i = 0; i < 10; i++) room.entities.create(Coin, { x: i * 5, y: 0, value: 1 });
  },
  onMessage(room, connection, message) {
    const id = (message as { collect?: unknown } | null)?.collect;
    const coin = typeof id === "number" ? room.entities.get(id) : undefined;
    if (coin?.kind !== Coin) return;
    room.entities.delete(coin);
    room.send(connection, { type: "collected", left: [...room.entities.all(Coin)].length });
  },
});
```

## See also

- [`RoomEntity`](/docs/room/room-entity)
- [State sync](/docs/room/guides/state-sync)
- [Ownership](/docs/room/guides/ownership)
