# Unity Multiplayer C# Events

Multiplayer exposes Game data-plane and room business events. All are code-only
`System.Action` events and are delivered after the related runtime state has
been committed.

## Connection Events

- `ConnectionChanged`: Reliable state changed.
- `ConnectionInterrupted`: a previously Ready Reliable lane failed or closed.
- `ConnectionRecovered`: automatic or explicit recovery of the retained current Match completed. Room state is already committed; GameStarted is not repeated.

When `ConnectionChanged` reports Ready, `CurrentRoomSnapshot` is readable and
internal peer routing is already installed. Reliable disconnect clears
internal peer routing before the failed/disconnected state is observed.

## Game Events

- `MessageReceived`: complete game custom, State or RPC messages. PeersSnapshot, runtime.finished and player-leave acknowledgements are consumed internally.
- `SceneGateChanged`: the independent RoomNode Scene Gate value changed.
- `ErrorOccurred`: runtime, protocol or transport error.

Voice, text, and emotion Host Session events belong to the optional GameKit
package. Multiplayer does not expose or process Service Messages.

Low-level peer packets are internal to integrations such as Mirror. Ping/pong
and handshake messages also remain internal. Gateway room commands are not exposed by Multiplayer.

## Errors

`IGPMultiplayerErrorEvent` includes `Code`, `Message`, `Source`, optional
`Transport`, `IsTerminal` and `Details`. Transport errors expose a stable code as
`Message`; socket exceptions and other internal exception objects are never placed
in the public event. `Details` is reserved for safe business metadata.

- `MULTIPLAYER_CONTEXT_INVALID` is emitted when the pre-connect bootstrap cannot
  create the requested runtime.
- `DATA_PLANE_PEER_CONTEXT_INVALID` is emitted when the Reliable handshake cannot
  provide the local/host routing context required by the SDK.

These errors do not represent SDK validation of robot identity, team policy,
membership policy or server slot-allocation policy.

## RoomChanged

```csharp
multiplayer.RoomChanged += change =>
{
    switch (change.Kind)
    {
        case IGPRoomChangeKind.Joined:
            // Initialize UI from change.Room and change.CurrentPlayer.
            break;
        case IGPRoomChangeKind.GameStarted:
            // This Match is ready. Start the game and apply all Changes below.
            goto case IGPRoomChangeKind.Updated;
        case IGPRoomChangeKind.GameEnded:
            // Arena ended this Match; Room.Status is finished.
            goto case IGPRoomChangeKind.Updated;
        case IGPRoomChangeKind.Updated:
            // Refresh from the complete snapshot. Multiple changes can coexist.
            if ((change.Changes & IGPRoomChangeFlags.Players) != 0)
            {
                foreach (var oldPlayer in change.PreviousRoom!.Players)
                {
                    bool remains = false;
                    foreach (var player in change.Room!.Players)
                        if (player.Id == oldPlayer.Id) { remains = true; break; }
                    if (!remains) OnPlayerLeft(oldPlayer.Id); // Your game handler.
                }
            }
            break;
        case IGPRoomChangeKind.Left:
            // Clear local room UI; change.PreviousRoom preserves the prior state.
            break;
    }
};
```

`IGPRoomChangedEvent` has read-only fields:

| Field | Type | Meaning / nullability |
| --- | --- | --- |
| Kind | IGPRoomChangeKind | Joined=0, Updated=1, Left=2, GameStarted=3, GameEnded=4 |
| PreviousRoom | IGPMultiplayerRoomSnapshot? | Complete previous value; null on Joined |
| Room | IGPMultiplayerRoomSnapshot? | Committed complete value; null on Left |
| CurrentPlayer | IGPMultiplayerPlayerSnapshot? | Current player; null on Left |
| Changes | IGPRoomChangeFlags | None=0, Players=1, Host=2, Status=4, Map=8, SceneGate=16 (reserved), Teams=32, Metadata=64; combinations allowed |
| Reason | string | Business reason: room-entered, players-updated, game-started, game-ended, room-left |

Room/player field definitions are in [Bootstrap Data Structures](README.md#bootstrap-data-structures).
These are the current immutable Core DTOs, not the deleted legacy mutable
`IGP.Multiplayer.Models.Room` / `Player` types. The event name and envelope are
restored; old lowercase field access must migrate to the documented Core DTOs.
There is no `RoomUpdated` alias or public transport/source payload.

SDK commits the room, player identity and Robots before the callback, delivered
on the Unity main thread. Subscribing does not replay state. First bootstrap
commits Joined before Ready; use ConnectionChanged for connection readiness.
Other players leaving emit Updated + Players, not local Left. The previous
snapshot remains intact. Slot-only changes and unconnected bots are not departures.
Identical Game snapshots are deduplicated. One GameStarted event can combine Players,
Host, Status and Map changes. Same-Match handoff is merged; a new Match in the same
room replaces the connection without Left/Joined. First Joined occurs before connection;
GameStarted occurs once after state/routing commit and ConnectionChanged(Ready).
Recovery commits Updated if needed before Ready and ConnectionRecovered. GameEnded
is committed once after the authoritative runtime.finished, with Status=finished.
Normal completion never initiates automatic recovery. Explicit local cleanup emits Left.

Players expose ConnectionState: Unknown=0 (old constructor default), Online=1,
Disconnected=2. Temporary disconnect retains the player; retirement removes a previously
known member. Unknown new players without full profile data are not fabricated.
MatchId, admission, slot and recovery credentials remain internal.

Missing descriptor identity reports MULTIPLAYER_MATCH_ID_REQUIRED; a conflicting
handshake reports MULTIPLAYER_MATCH_ID_MISMATCH. Neither publishes Ready or GameStarted.
After an established Reliable interruption, automatic recovery tries once. Concurrent
manual calls share that task. Failure reports MULTIPLAYER_RECONNECT_FAILED and does not
loop; a later explicit call can try again. See [recovery flow](CONNECTION-RECONNECT.md).

Callback exceptions are logged without exception/body text and do not prevent
other subscribers from receiving the event. No credentials enter this payload.

`IGPRoomChangedEvent.EntryKind` 在 GameStarted 为 `IGPMatchEntryKind.Initial` / `Reentry`，其他事件、旧服务端缺失字段或未知值为 `Unknown`。新进程重返仍按正常 Joined → Ready → GameStarted；进程内恢复不重复 GameStarted。完整流程见 [连接与重连](CONNECTION-RECONNECT.md)。
