Skip to content
Download all docs .md

Unity C# Client Reference

The GameFuse C# SDK (game-fuse-cs) has a multiplayer client for Unity. It joins the same rooms, runs the same room code and has the same shape as the browser client, so a Unity player and a browser player can be in one room together.

It is plain C# (ClientWebSocket and HttpClient) with a small Unity layer on top. Desktop, mobile and the Unity editor are supported.

Not on WebGL yet

Unity WebGL builds cannot use System.Net.WebSockets.ClientWebSocket, so this client does not run there. A WebGL game can call the browser client through a .jslib plugin instead.

Install

Add the package to your Unity project from Git (Package Manager, "Add package from git URL"):

https://github.com/GameFuseCo/game-fuse-cs.git?path=com.gamefuse.sdk

The multiplayer code is in Runtime/Multiplayer, in the GameFuseCSharp namespace.

A whole session

using System.Collections.Generic;
using GameFuseCSharp;
using UnityEngine;

public class Match : MonoBehaviour
{
    GameFuseMultiplayer mp;
    GameFuseRoom room;

    void Start()
    {
        GameFuse.SetUpGame("Your Game ID", "Your Game Token", OnGameSetUp);
    }

    async void OnGameSetUp(string message, bool hasError)
    {
        if (hasError) { Debug.LogError(message); return; }

        mp = GameFuseMultiplayerUnity.Create();      // plays as the signed-in GameFuseUser, if any
        if (!mp.IsSignedIn) await mp.SignInAsGuest(); // otherwise as a guest

        try
        {
            room = await mp.Resume()
                ?? await mp.JoinQueue("1v1", new Dictionary<string, object> { { "clientVersion", "1" } });
        }
        catch (GameFuseMultiplayerException e)
        {
            Debug.LogError(e.Code + ": " + e.Message);   // "no_match", "rejected", "cancelled", "busy" or null
            return;
        }

        room.OnMessage((type, data) => Debug.Log("Got " + type));
        room.OnPlayers(players => Debug.Log(players.Count + " players"));
        room.OnReconnecting(() => Debug.Log("Connection lost, getting back in..."));
        room.OnReconnected(() => Debug.Log("Back in"));
        room.OnClosed((reason, detail) => Debug.Log("Room closed: " + reason));
    }

    void Update()
    {
        if (room != null && !room.IsClosed && Input.GetKeyDown(KeyCode.Space))
            room.Send("move", new Dictionary<string, object> { { "x", 1 }, { "jump", true } });
    }

    void OnDestroy()
    {
        if (room != null) room.Leave();
    }
}

GameFuseMultiplayerUnity.Create()

Makes the client for you. It:

  • takes the game ID and token you passed to GameFuse.SetUpGame, so call it after setup has finished;
  • plays as the signed-in GameFuseUser if there is one;
  • keeps a guest's token in PlayerPrefs, so a guest is the same player the next time the game runs;
  • adds a dispatcher that runs your event listeners on Unity's main thread, once a frame.

Signing in

Call What it does
await mp.SignInAsGuest() Plays as a guest. The guest is made once, then reused.
mp.UseGameFuseUser() Plays as the player signed in with the GameFuse SDK.
mp.UseToken(token) Plays as any GameFuse player, given their authentication token.
mp.IsSignedIn True once one of the above has been done.

Getting into a room

Each call returns a task for a GameFuseRoom. The options you pass reach your room code as player.options.

Call What it does
await mp.JoinQueue(queue, options) Joins a queue. The queue name is the game mode. Pass clientVersion in options; only players with the same one are matched.
mp.LeaveQueue() Stops waiting. The waiting JoinQueue throws with Code == "cancelled".
await mp.CreateRoom() / await mp.CreateRoom(gameMode, options) Makes a private room. Share room.Code.
await mp.JoinRoom(code, options) Joins a private room by its 6-character code.
await mp.Resume() The room the game was in before it restarted, or null.

A failed join throws GameFuseMultiplayerException. Its Code is the same as the browser client's error.code: "no_match", "rejected", "cancelled" or "busy".

The room

Member Meaning
room.Code The room's 6-character code.
room.Me You: Id, Name, Seat.
room.Players The latest player list.
room.IsClosed True after OnClosed.
room.Send(type, data) Sends to your room code's message(room, player, type, data). At most 4 KB and 60 a second.
room.Leave() Leaves on purpose. Your room code sees playerLeft with 'quit'.

Message data is null, bool, long, double, string, List<object> or Dictionary<string, object>, the same values JSON has.

Events

Each On... call returns an Action that removes the listener.

Event Arguments When
OnMessage (string type, object data) Your room code sent you something. Messages that arrive before you add a listener are kept for it.
OnPlayers (IReadOnlyList<GameFuseRoomPlayer> players) The player list changed. Each player has Id, Name, Seat, Connected.
OnReconnecting () Your connection dropped and the client is getting back in.
OnReconnected () You are back in the same seat.
OnClosed (string reason, string detail) You are out of the room: "ended", "kicked", "lost", "left", "error" or "no_match". See the browser client for what each means.

Outside Unity

The core has no UnityEngine code, so it also runs in a .NET server, tool or test. Make the client yourself:

var mp = new GameFuseMultiplayer(new GameFuseMultiplayerOptions
{
    GameId = "12",
    GameToken = "your-game-api-token",
    DispatchImmediately = true,   // default false: call mp.DispatchEvents() from your own loop
    // AutoReconnect = false,     // get OnClosed("lost") at once when the connection drops
    // Storage = new MyStorage(), // IGameFuseMultiplayerStorage; the default keeps the guest in memory
});

With DispatchImmediately = true, listeners run on a background thread.

Next