MultiConnectMultiConnectDocs Website home
MultiConnectSDK › Developer Guide

10. Room Communication

Client-Side Messaging

Script 10.1

// Get current room
Room room = GameRooms.GetActiveRoom();
// or
Room room = GameRooms.GetRoom("roomId");

// Send to server (TCP for reliable, UDP for fast)
room.SendMcBinary(data, GameMessage.PlayerMove, McProtocol.Unreliable);
room.SendMcBinary(data, GameMessage.ChatMessage, McProtocol.Reliable);

// Add listeners
room.AddResponseListener(GameMessage.PlayerMove, OnPlayerMove);
room.AddPermanentResponseListener(GameMessage.GameState, OnGameState); // Survives scene changes

// Remove listeners
room.RemoveListener(GameMessage.PlayerMove);
room.RemoveAllListener();

// Leave room
room.LeaveRoom();

Server-Side Messaging

Script 10.2

// Send to specific player
room.SendMcBinaryTo(playerId, data, GameMessage.PrivateMessage, McProtocol.Reliable);

// Send to all players (including spectators)
room.SendMcBinaryToAll(data, GameMessage.GameUpdate, McProtocol.Reliable);

// Send to specific spectator
room.SendMcBinaryToSpectator(spectatorId, data, GameMessage.SpectatorUpdate, McProtocol.Reliable);

// Add listeners for client messages
room.AddResponseListener(GameMessage.PlayerAction, OnPlayerAction);
room.AddPermanentResponseListener(GameMessage.ChatMessage, OnChatMessage);

// Room control
room.isOpen = false;  // Stop accepting new players
room.LeaveRoom(playerId, "Kicked for cheating");
room.RemoveSpectator(spectatorId);
room.DestroyRoom();

Knowing Who Sent a Message

A message only contains what the sending client put in it, so a field such as playerId inside your message class says who the client claims to be. To know who really sent it, give the listener a function with two parameters, as in Script 10.3. The first is the sender's id, which MultiConnectSDK takes from the player's connection, not from the message, so another player cannot fake it.

Script 10.3: Listening with the sender's id

public void OnRoomCreated(Room room)
{
    this.room = room;
    room.AddPermanentResponseListener(GameMessage.PlayerAction, OnPlayerAction);
}

void OnPlayerAction(string senderId, object obj)
{
    var action = (PlayerActionData)obj;
    if (senderId != currentTurnPlayerId) return; // Not this player's turn
    // ...apply the action for senderId
}