MultiConnectSDK › Developer Guide
8. Client Reference
The MultiConnectClient component
- Create an empty GameObject named
"MultiConnectClient" - Add the
MultiConnectClientcomponent - Set Sdk Key to your key and leave Use Custom Hosting off. Nothing else is needed to reach your deployment.
| Field | Description |
|---|---|
| Sdk Key | Your key from Game Analytics on the dashboard, the same on clients and servers |
| Initialize On Start | On to start by itself; off to call InitializeMultiConnect from code |
| Use Custom Hosting | Off for MultiConnectCloud |
| Connect To Local Server | Test against a server on your machine. Works only in the Editor and Development Builds |
| Local Server Address | Where that server is, such as 127.0.0.1:7777 |
| Use UDP | Enable McProtocol.Unreliable (UDP; WebRTC in WebGL builds) |
| Use Web Rtc On WebGL | WebGL: carry Unreliable on a WebRTC data channel (default on) |
| Is Development Build | Enable logging during development |
| Allowed Logs | Select log categories to display |
A complete client
This script uses your own message types, such as GameMessage. Define yours in one shared file, as in Script 2.1 and Script 7.6.
Script 8.1: NetworkManager.cs
using System.Collections.Generic;
using System;
using MultiConnect.Client;
using MultiConnect.Global;
using MultiConnect.Serialization;
using MultiConnect.Unity;
using MultiConnect;
using UnityEngine;
public class NetworkManager : MonoBehaviour
{
[Header("Room Configuration")]
[SerializeField] private int maxPlayers = 4;
[SerializeField] private int minPlayers = 2;
private Room currentRoom;
void Start()
{
// Subscribe to initialization event (optional)
MultiConnectInfo.onMultiConnectInitialized += OnMultiConnectReady;
// If InitializeOnStart is disabled in Inspector, initialize manually:
// MultiConnectClient.instance.InitializeMultiConnect("YOUR_SDK_KEY");
// Or check if already initialized
if (MultiConnectInfo.IsMultiConnectInitialized())
{
SetupConnectionEvents();
}
}
void OnMultiConnectReady()
{
Debug.Log("MultiConnect initialized!");
SetupConnectionEvents();
}
void SetupConnectionEvents()
{
// Connection events
// The first server a client reaches is its matchmaker: a combined server or a master.
Client.onMasterServerConnected += OnConnectedToServer;
Client.onMasterServerDisConnected += OnDisconnectedFromServer;
Client.onNetworkChange += OnNetworkChanged;
// Room events
GameRooms.OnRoomJoined += OnRoomJoined;
GameRooms.OnRoomJoinedFailed += OnRoomJoinFailed;
GameRooms.OnPrivateRoomJoined += OnPrivateRoomJoined;
GameRooms.OnPrivateRoomJoinedFailed += OnPrivateRoomFailed;
GameRooms.OnOfflineRoomJoined += OnOfflineRoomJoined;
}
// ═══════════════════════════════════════════════════════════
// CONNECTION
// ═══════════════════════════════════════════════════════════
// MultiConnectCloud finds your deployment from the SDK key, in the region you ask for.
public async void ConnectToServer(string playerId)
{
bool found = await Client.ConnectToServer(ServerRegions.Any, playerId);
if (!found) Debug.LogWarning("No server is available right now. Try again shortly.");
}
void OnConnectedToServer(bool isReconnect)
{
Debug.Log(isReconnect ? "Reconnected to server!" : "Connected to server!");
Debug.Log($"My ID: {Client.MyID}");
// Now you can find/create rooms
}
void OnDisconnectedFromServer()
{
Debug.LogWarning("Disconnected from server!");
currentRoom = null;
}
void OnNetworkChanged()
{
Debug.Log("Network changed (WiFi/Mobile switch)");
}
// ═══════════════════════════════════════════════════════════
// MATCHMAKING - PUBLIC ROOMS
// ═══════════════════════════════════════════════════════════
public void FindPublicRoom()
{
var roomParams = new Dictionary<string, string>
{
{ "gameMode", "deathmatch" },
{ "map", "desert" }
};
GameRooms.FindRoom(
parameters: roomParams,
maxPlayers: maxPlayers,
minPlayers: minPlayers,
removePlayerTime: 30, // Wait 30s for reconnect
timeToDestroyRoom: 60, // Destroy after 60s if empty
CheckNotEqual: "", // Optional: prevent same-value matching
playerData: "{\"level\":10}" // Optional: player data for server
);
}
// ═══════════════════════════════════════════════════════════
// PRIVATE ROOMS
// ═══════════════════════════════════════════════════════════
public void CreatePrivateRoom(string roomId, string password)
{
var roomParams = new Dictionary<string, string>
{
{ "gameMode", "custom" }
};
GameRooms.CreatePrivateRoom(
parameters: roomParams,
maxPlayers: maxPlayers,
minPlayers: 1,
removePlayerTime: 60,
timeToDestroyRoom: 300,
RoomID: roomId, // Custom room ID
RoomPassword: password,
PlayerData: "{\"isHost\":true}",
EntryAmt: 0f, // Entry fee (0 = free)
SpectatorCnt: 2 // Max spectators
);
}
public void JoinPrivateRoom(string roomId, string password)
{
GameRooms.JoinPrivateRoom(
roomID: roomId,
roomPassword: password,
PlayerData: "{\"isHost\":false}",
PlayerBalance: 0f
);
}
public void JoinAsSpectator(string roomId, string spectatorId, string password = "")
{
GameRooms.JoinAsSpectator(
roomID: roomId,
SpectatorID: spectatorId,
roomPassword: password
);
}
// ═══════════════════════════════════════════════════════════
// OFFLINE ROOM (Practice/Single Player)
// ═══════════════════════════════════════════════════════════
public void CreateOfflineRoom()
{
var roomParams = new Dictionary<string, string>
{
{ "mode", "practice" }
};
GameRooms.CreateOfflineRoom(
parameters: roomParams,
maxPlayers: 1,
minPlayers: 1,
PlayerData: "{\"aiEnabled\":true}"
);
}
// ═══════════════════════════════════════════════════════════
// ROOM EVENT HANDLERS
// ═══════════════════════════════════════════════════════════
void OnRoomJoined(Room room)
{
Debug.Log($"Joined room: {room.roomId}");
currentRoom = room;
// Set as active room
GameRooms.SetRoomsAsActive(room.roomId);
// Setup room message listeners
SetupRoomListeners(room);
// Load game scene
// SceneManager.LoadScene("GameScene");
}
void OnRoomJoinFailed(string message, int errorCode)
{
Debug.LogError($"Failed to join room: {message} (Code: {errorCode})");
}
void OnPrivateRoomJoined(Room room)
{
Debug.Log($"Joined private room: {room.roomId}");
currentRoom = room;
SetupRoomListeners(room);
}
void OnPrivateRoomFailed(string message, int errorCode)
{
Debug.LogError($"Private room failed: {message} (Code: {errorCode})");
}
void OnOfflineRoomJoined(Room room)
{
Debug.Log($"Offline room created: {room.roomId}");
currentRoom = room;
SetupRoomListeners(room);
}
// ═══════════════════════════════════════════════════════════
// ROOM COMMUNICATION
// ═══════════════════════════════════════════════════════════
void SetupRoomListeners(Room room)
{
// Add listeners for game messages
room.AddResponseListener(GameMessage.PlayerMove, OnPlayerMove);
room.AddResponseListener(GameMessage.GameStart, OnGameStart);
room.AddResponseListener(GameMessage.PlayerJoined, OnOtherPlayerJoined);
room.AddResponseListener(GameMessage.PlayerLeft, OnOtherPlayerLeft);
}
public void SendPlayerPosition(Vector3 position, float rotation)
{
if (currentRoom == null) return;
var moveData = new PlayerMoveData
{
playerId = Client.MyID,
x = position.x,
y = position.y,
z = position.z,
rotation = rotation
};
// Use UDP for frequent position updates
currentRoom.SendMcBinary(moveData, GameMessage.PlayerMove, McProtocol.Unreliable);
}
public void SendChatMessage(string message)
{
if (currentRoom == null) return;
var chatData = new ChatMessageData
{
playerId = Client.MyID,
message = message,
timestamp = System.DateTime.UtcNow
};
// Use TCP for reliable delivery
currentRoom.SendMcBinary(chatData, GameMessage.ChatMessage, McProtocol.Reliable);
}
void OnPlayerMove(object obj)
{
var moveData = (PlayerMoveData)obj;
Debug.Log($"Player {moveData.playerId} moved to ({moveData.x}, {moveData.y}, {moveData.z})");
}
void OnGameStart(object obj)
{
Debug.Log("Game starting!");
}
void OnOtherPlayerJoined(object obj)
{
var data = (PlayerJoinedData)obj;
Debug.Log($"Player joined: {data.playerId}");
}
void OnOtherPlayerLeft(object obj)
{
var data = (PlayerLeftData)obj;
Debug.Log($"Player left: {data.playerId}");
}
// ═══════════════════════════════════════════════════════════
// CLEANUP
// ═══════════════════════════════════════════════════════════
public void LeaveCurrentRoom()
{
if (currentRoom != null)
{
currentRoom.RemoveAllListener();
currentRoom.LeaveRoom();
currentRoom = null;
}
}
void OnApplicationQuit()
{
LeaveCurrentRoom();
Client.DisconnectFromServer();
}
void OnDestroy()
{
// Unsubscribe from events
Client.onMasterServerConnected -= OnConnectedToServer;
Client.onMasterServerDisConnected -= OnDisconnectedFromServer;
Client.onNetworkChange -= OnNetworkChanged;
GameRooms.OnRoomJoined -= OnRoomJoined;
GameRooms.OnRoomJoinedFailed -= OnRoomJoinFailed;
GameRooms.OnPrivateRoomJoined -= OnPrivateRoomJoined;
GameRooms.OnPrivateRoomJoinedFailed -= OnPrivateRoomFailed;
GameRooms.OnOfflineRoomJoined -= OnOfflineRoomJoined;
MultiConnectInfo.onMultiConnectInitialized -= OnMultiConnectReady;
}
}
// ═══════════════════════════════════════════════════════════
// DATA CLASSES (Keep in shared location)
// ═══════════════════════════════════════════════════════════
[McSerializationObject]
public class PlayerMoveData
{
public string playerId;
public float x;
public float y;
public float z;
public float rotation;
}
[McSerializationObject]
public class ChatMessageData
{
public string playerId;
public string message;
public DateTime timestamp;
}
[McSerializationObject]
public class PlayerJoinedData
{
public string playerId;
public string playerData;
}
[McSerializationObject]
public class PlayerLeftData
{
public string playerId;
public string reason;
}
Connecting on your own servers
Everything else in this section stays the same, except that you tick Use Custom Hosting, keep your servers' addresses yourself, and replace ConnectToServer:
Script 8.2: OwnServerConnection
public class OwnServerConnection
{
public void Connect(string serverIP, int serverPort)
{
var protocols = new List<McProtocol> { McProtocol.Reliable };
if (MultiConnectClient.instance.useUDP) protocols.Add(McProtocol.Unreliable);
Client.ConnectToServer(
IP_Addr: serverIP,
PORT: serverPort,
wsURL: "ws://" + serverIP + ":" + serverPort,
ProtocolsToUse: protocols,
isMasterServer: true, // Combined or Master server: true. Dedicated game server: false
UniqueClientID: "" // Leave empty for a generated ID
);
}
}
Use WebSocket decides between that URL and raw TCP. For WebGL or wss://, the server must listen for WebSocket too. On MultiConnectCloud the deployment's WebSocket setting decides this for you, and TLS is already in place.

