Skip to main content

Accelbyte logo

With Idem you can add matchmaking to any Unity game in no time.

We are actively working on the Idem Unity SDK which will go into beta soon. If you want to join the beta, get in touch to be put on the list for early access.

Until then, you can use the following snippet to get started and build on this using the WebSocket API docs and the instructions for Setting up Player-based.

Sample implementation

Below you can find sample code to get started with integrating Idem into your Unity game.

For the default setup (1v1 on beta), simply add your JOIN_CODE to make the script ready after completing the simple steps A - C of the Setting up Player-based guide. Then, execute ConnectToWebSocket and addPlayerToQueue from two clients to trigger the matchmaking. This will lead to a console output similar to this:

Example of Unity console output after successful matchmaking.

Unity console example output

Sample code

IdemMatchmakingManager.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
using UnityEngine;
using Newtonsoft.Json.Linq;

public class IdemMatchmakingManager : MonoBehaviour
{
private ClientWebSocket webSocket;
private const string WEBSOCKET_API_URL = "wss://ws.int.idem.gg";
private const string JOIN_CODE = "<ADD JOIN CODE HERE>";
private const string GAME_ID = "1v1";
private const string PLAYER_AUTH = "Demo";
private string playerId;
private readonly Dictionary<string, int> SERVER = new Dictionary<string, int>
{
{ "my_server1", 1 },
{ "my_server2", 1 }
};

private void Start()
{
playerId = GenerateRandomPlayerId(8); // Generates a random player ID for testing
}

// Public method to connect to the WebSocket
public async void ConnectToWebSocket()
{
if (webSocket != null && webSocket.State == WebSocketState.Open)
{
Debug.LogWarning("WebSocket is already connected.");
return;
}

string uri = $"{WEBSOCKET_API_URL}/?playerId={playerId}&code={JOIN_CODE}&authorization={PLAYER_AUTH}";
webSocket = new ClientWebSocket();

try
{
Debug.Log("Connecting to WebSocket.");
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Debug.Log("Connected to WebSocket.");

// Start listening for messages
_ = Task.Run(ReceiveMessages);
}
catch (Exception e)
{
Debug.LogError("WebSocket connection failed: " + e.Message);
}
}

// Public method to add the player to the matchmaking queue
public async void AddPlayerToQueue()
{
if (webSocket == null || webSocket.State != WebSocketState.Open)
{
Debug.LogWarning("WebSocket is not connected. Please connect first.");
return;
}

// Directly convert the SERVER dictionary into a JObject
var serversObject = JObject.FromObject(SERVER);

var request = new JObject
{
["action"] = "addPlayer",
["payload"] = new JObject
{
["players"] = new JArray
{
new JObject
{
["playerId"] = playerId,
["servers"] = serversObject
}
},
["partyName"] = playerId,
["gameId"] = GAME_ID
}
};

string message = request.ToString();
byte[] bytes = Encoding.UTF8.GetBytes(message);

await webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
Debug.Log("Sent addPlayer request to WebSocket.");
}


private async Task ReceiveMessages()
{
var buffer = new byte[1024 * 4];

while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
Debug.Log("WebSocket connection closed.");
break;
}

string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
ProcessMessage(message);
}
}

private void ProcessMessage(string message)
{
Debug.Log("Received message from WebSocket: " + message);
}


private string GenerateRandomPlayerId(int length)
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var random = new System.Random();
var playerId = new char[length];
for (int i = 0; i < length; i++)
{
playerId[i] = chars[random.Next(chars.Length)];
}
return new string(playerId);
}

private async void OnApplicationQuit()
{
if (webSocket != null && webSocket.State == WebSocketState.Open)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Application ending", CancellationToken.None);
webSocket.Dispose();
}
}
}