# Entities: get() method

> The get() method of the Entities interface returns the entity with an ID, or the entity of a kind with a key.

The **`get()`** method of the [`Entities`](/docs/room/entities) interface returns the entity with an ID, or the live entity of a kind whose key field holds a key.

## Syntax

```ts
get(id)
get(kind, key)
```

### Parameters

`id`
: An entity ID.

`kind`
: A kind declared with a `key`.

`key`
: The value of the kind's key field to look for.

### Return value

The [`RoomEntity`](/docs/room/room-entity), or `undefined` when there's none.

- `get(id)` gives `room.state` for ID 0, and `undefined` for an ID no live entity has. It never gives private state or a presence entry.
- `get(kind, key)` gives the entity typed as its kind, so its fields need no cast.

### Exceptions

`TypeError`
: Thrown by `get(kind, key)` if the kind has no key.

## Description

Both forms are map lookups, whatever the number of entities, unlike [`all()`](/docs/room/entities/all), which visits every entity of a kind.

A kind's key names one of its `string` fields, such as a player ID or a name from a level file. The key of a live entity is set at `create()`, never empty, unique within the kind, and fixed for the entity's life; deleting the entity frees it. Keys are room state, so lookups work the same after a wake. See [Entity IDs and lookups](/docs/room/guides/state-sync#entity-ids-and-lookups).

`get(id)` returns an entity typed with no particular kind. Compare its `kind` with your kind, or cast it, before reading fields.

## Examples

### Finding a player's character by player ID

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

const Hero = entity("hero", { player: "string", hp: "u16", gold: "u32" }, { key: "player" });

export default defineRoom({
  schema: defineSchema({ entities: [Hero] }),
  onJoin(room, connection) {
    const hero = room.entities.get(Hero, connection.player) ?? room.entities.create(Hero, { player: connection.player, hp: 100 });
    room.send(connection, { type: "hero", id: hero.id, gold: hero.gold });
  },
});
```

### Reaching a tile by a computed ID

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

const Tile = entity("tile", { crop: "u8" });
const WIDTH = 32;
const tileId = (x: number, y: number) => 2 + x + y * WIDTH;

export default defineRoom({
  schema: defineSchema({ entities: [Tile] }),
  onCreate(room) {
    for (let y = 0; y < WIDTH; y++) for (let x = 0; x < WIDTH; x++) room.entities.create(Tile, {}, { id: tileId(x, y) });
  },
  onMessage(room, _connection, message) {
    const plant = (message as { plant?: { x: number; y: number } } | null)?.plant;
    if (!plant) return;
    const tile = room.entities.get(tileId(plant.x, plant.y));
    if (tile?.kind === Tile) tile.crop = 1;
  },
});
```

## See also

- [`Entities.all()`](/docs/room/entities/all)
- [Entity IDs and lookups](/docs/room/guides/state-sync#entity-ids-and-lookups)
