Skip to article Developer portalAdd your game

SPLITSCREEN CLUB / DOCUMENTATION

Unity

The Unity package (sdk/unity, com.ontola.gamenight) handles the connection, the session lifecycle, every player's controller by seat, names, colours and faces, match settings, phone buttons, plain-text requests, phone screens, saved progress, the room log, rumble and the game window. Your game connects these to its own simulation and rendering.

Orb Rush in examples/unity-demo is the reference game: a small 3D couch game that uses every feature on this page. The code below is read from it, so it is the code that runs. Copy the project to start your own game.

Install

In Unity 2021.3 or later, open Window → Package Manager → + → Add package from git URL and enter:

https://github.com/ontola/gamepad-party.git?path=/sdk/unity

Or add it to Packages/manifest.json, pinned to a commit or tag:

"com.ontola.gamenight": "https://github.com/ontola/gamepad-party.git?path=/sdk/unity#main"

The package is plain C# with no other dependencies. It reads keyboard and pad input through the Input System when that package is installed and active, and through the old Input Manager otherwise.

Player settings

These are the settings every Splitscreen Club game needs. Orb Rush applies them from its build script:

public static void ApplyPlayerSettings()
{
    PlayerSettings.productName = "Orb Rush";
    PlayerSettings.companyName = "GameNight";
    // Keep running while another game or the lobby has focus: a warming
    // game that stops updating never hears Start.
    PlayerSettings.runInBackground = true;
    PlayerSettings.visibleInBackground = true;
    // Start windowed and small; the SDK takes borderless fullscreen on
    // Start. Never exclusive fullscreen: no display-mode switch between games.
    PlayerSettings.fullScreenMode = FullScreenMode.Windowed;
    PlayerSettings.defaultScreenWidth = 1280;
    PlayerSettings.defaultScreenHeight = 720;
    PlayerSettings.resizableWindow = true;
    PlayerSettings.forceSingleInstance = false;
    // No splash: Start must show gameplay within a second.
    PlayerSettings.SplashScreen.show = false;
}

Source: examples/unity-demo/Assets/Editor/BuildOrbRush.cs

Run in Background matters most. Splitscreen Club prepares the next game while another one is on screen; a Unity player that stops updating when it loses focus never hears Start. The package also sets it at startup when Splitscreen Club launched the game, but set it in the project too.

Connect

GameNight.Client is the connection. Touch it once, from Awake, and the package creates a hidden GameNight object that pumps it every frame before your scripts run, also while Time.timeScale is 0. You never put it in a scene. Set your catalog id first:

// The catalog id. Under GameNight, GAMENIGHT_GAME_ID decides.
GameNight.Configure("unity-demo");
var gn = GameNight.Client;

Source: examples/unity-demo/Assets/OrbRush/OrbRushView.cs

The same build runs standalone and under Splitscreen Club. Splitscreen Club launches it with GAMENIGHT=1 and the address in the environment, and GameNight.Client.LaunchedByHost is true: skip your menus and wait for Prepared. A game you start by hand stays offline, so a test run never joins the party on your machine. To connect it to a development host anyway, set GAMENIGHT_ADDR=127.0.0.1:7912 or call GameNight.Configure(id, connectStandalone: true).

Every event fires on the main thread, inside that pump. When Splitscreen Club goes away, a launched game quits.

Lifecycle

Subscribe once. The package re-declares your settings, phone buttons, phone screen and plain-text requests after every reconnect, so declare them in Connected:

void Wire()
{
    var gn = GameNight;
    // Declaring once is enough: the SDK re-declares after every reconnect.
    gn.Connected += () =>
    {
        gn.DeclareSettings(Settings);
        gn.DeclareActions(Actions);
        gn.DeclareCommands("Change Orb Rush while you play: the number of orbs, the round length, or a new round.",
            "8 orbs", "rounds of 90 seconds", "new round");
        PhoneScreenFolder?.Invoke();
    };
    gn.Prepared += OnPrepared;
    gn.Started += _ => SetPaused(false);
    gn.Resumed += _ => SetPaused(false);
    gn.Paused += _ => SetPaused(true);
    gn.Disposed += _ =>
    {
        Session = "";
        MenuOwner = -1;
        SetPaused(true);
        Trace("disposed");
    };

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Prepared loads the level while hidden and silent, then reports Ready. Start begins play at once. Pause must freeze gameplay, timers and sound; Resume continues the same match. Dispose clears the session, and a new Prepared may follow later in the night, in the same process:

void OnPrepared(string session, IReadOnlyList<Seat> seats, IReadOnlyList<Player> players)
{
    Session = session;
    // Live roster updates; a newcomer can join this match at once.
    GameNight.NotifyParticipation(session, instantJoin: true);
    GameNight.NotifyProgress(session, 10, "building the arena");
    SeatRunners(seats);
    NewRound(log: false);
    SetPaused(true);
    GoldUnlocked = GameNight.PartyUnion().Contains(GoldFloor);
    var names = new List<string>();
    foreach (var r in Runners) names.Add(r.Bot ? "bot" : $"{r.Name} (seat {r.Seat})");
    Trace("seated " + string.Join(", ", names));
    GameNight.NotifyProgress(session, 100);
    // Ready only once the first frame can be drawn: the level is built above.
    GameNight.NotifyReady(session);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Call NotifyReady only when the first frame can be drawn. NotifyProgress is optional: send it when loading takes more than a moment, so the lobby can show a real bar. NotifyParticipation from Prepared opts into live roster updates; pass instantJoin: true only when a running match can take a new player at once.

NotifyFinished(session) reports a round. It changes nothing else: your game keeps its own results screen and starts the next round itself.

Controllers

Seats are players. A seat's controller token is opaque; it is not a Unity joystick index, and the order of pads Unity sees means nothing under Splitscreen Club. FrameForSeat(seat) returns that seat's input from the host. It is neutral while the session is not running and when the input is more than 250 ms old:

(float x, float y) Read(Runner r)
{
    PadInput input;
    if (r.Bot) input = BotInput(r);
    else if (r.Seat >= 0)
    {
        // GameNight's input for this seat: neutral while paused or stale.
        var frame = GameNight.FrameForSeat(r.Seat);
        var (sx, sy) = Pad.Stick(frame);
        input = new PadInput { X = sx, Y = sy, Buttons = frame.Buttons };
    }
    else input = _localInput != null ? _localInput(r) : default;
    var mx = input.X;
    var my = input.Y;
    var held = input.Buttons;
    // Menu navigation uses the stick like a d-pad: one step per push.
    if (mx < -0.6f) held |= 1 << Pad.Left;
    if (mx > 0.6f) held |= 1 << Pad.Right;
    if (my < -0.6f) held |= 1 << Pad.Up;
    if (my > 0.6f) held |= 1 << Pad.Down;
    r.Pressed = held & ~r.Held;
    r.Held = held;
    var length = (float)Math.Sqrt(mx * mx + my * my);
    return length > 1f ? (mx / length, my / length) : (mx, my);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Pad names every button and axis (Pad.A to Pad.Right). Pad.Stick and Pad.Trigger apply the deadzones our games settled on (0.15 and 0.06). On the wire, up on a stick is negative y; GameNight.Stick(seat) gives a Vector2 with up positive, as Unity expects. GameNight.JustPressed(seat, Pad.A) is true in the one frame a button went down; read it in Update, not FixedUpdate. After Start and Resume, a button still held from the lobby must be released first, so the press that started the game does not also fire in it.

Back/Select belongs to Splitscreen Club: the host pauses you and shows the lobby. Never bind it. F1 does the same from a keyboard; the package handles it.

ReportActivity(seat) on a press or a stick past its deadzone keeps the player from being marked asleep. It sends at most once a second per pad. Rumble(seat, weak, strong, seconds) vibrates a seat's pad, both strengths 0 to 1; standalone it drives the local pad through the Input System.

Standalone, read your own pads and keyboard. Orb Rush does that in OrbRushView.ReadLocal, and only there.

The Start menu

Every Splitscreen Club game has the same Start menu: the game's name, Resume, New round (which applies the options), then the settings. No button hints. Play waits while it is open:

bool Menu()
{
    if (MenuOwner < 0)
    {
        for (var i = 0; i < Runners.Count; i++)
        {
            if (Runners[i].Bot || !Runners[i].Pressing(Pad.Start)) continue;
            MenuOwner = i;
            MenuRow = 0;
            Trace("menu open");
            return true;
        }
        return false;
    }
    var p = Runners[MenuOwner];
    var rows = MenuItems.Length + MenuSettings;
    if (p.Pressing(Pad.Start) || p.Pressing(Pad.B)) { CloseMenu(); return true; }
    if (p.Pressing(Pad.Up)) MenuRow = (MenuRow + rows - 1) % rows;
    if (p.Pressing(Pad.Down)) MenuRow = (MenuRow + 1) % rows;
    if (p.Pressing(Pad.A) && MenuRow < MenuItems.Length)
    {
        if (MenuItems[MenuRow] == "New round") NewRound();
        CloseMenu();
        return true;
    }
    var step = (p.Pressing(Pad.Right) ? 1 : 0) - (p.Pressing(Pad.Left) ? 1 : 0);
    if (step != 0 && MenuRow >= MenuItems.Length)
    {
        var setting = Settings[MenuRow - MenuItems.Length];
        var value = setting.Key == "round_seconds" ? RoundSeconds + step * 10 : OrbCount + step;
        OnSetting(setting.Key, value);
        // Tell GameNight, so the phones and the assistant see the same value.
        if (GameNight.LaunchedByHost) GameNight.SetSetting(setting.Key, setting.Key == "round_seconds" ? RoundSeconds : OrbCount);
    }
    return true;
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

A value changed in the menu goes through SetSetting, so the phones and the assistant show the same value.

Settings

Declare the settings the party may change from their phones or by asking the assistant. Mark a setting PerPlayer() when every player picks their own value, such as a character; it is saved with their profile between nights:

public static readonly Setting[] Settings =
{
    Setting.Number("round_seconds", "Round length in seconds (next round)", 60, 20, 180),
    Setting.Number("orbs", "Orbs on the field", 6, 2, 16),
    Setting.Toggle("bumps", "Dashes knock players away", true),
    Setting.Choice("body", "Your shape", "ball", "ball", "cube", "capsule").PerPlayer()
        .Describe("Each player picks their own shape; it is saved with their profile."),
};

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Values arrive through SettingChanged, and per-player values through PlayerSettingsChanged and PlayerSetting(playerId, key). Apply a value live when that is safe, or at the next round, and say which in the label:

public void OnSetting(string key, object value)
{
    switch (key)
    {
        case "round_seconds": RoundSeconds = Clamp((int)Json.ToLong(value, RoundSeconds), 20, 180); break;
        case "orbs":
            OrbCount = Clamp((int)Json.ToLong(value, OrbCount), 2, 16);
            while (Orbs.Count < OrbCount) Orbs.Add(FreeSpot());
            while (Orbs.Count > OrbCount) Orbs.RemoveAt(Orbs.Count - 1);
            break;
        case "bumps": Bumps = value is bool b ? b : Bumps; break;
        default: return;
    }
    Trace($"setting {key} = {Json.Write(value)}");
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Phone buttons and requests in words

Phone buttons sit next to your settings on every player's phone, for things that happen once. Presses arrive through ActionTriggered, only while your session is the one being played:

public static readonly PhoneAction[] Actions =
{
    new PhoneAction("new_round", "New round", confirm: true, description: "Ends this round for everyone."),
    new PhoneAction("shuffle", "Shuffle the orbs"),
};

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

DeclareCommands accepts requests in plain words from the Splitscreen Club app and the session assistant ("8 orbs", "rounds of 90 seconds"). Your game decides what the words mean and answers once:

void OnCommand(GameCommand command)
{
    var text = command.Text.ToLowerInvariant();
    var number = Regex.Match(text, @"\d+");
    if (text.Contains("new round") || text.Contains("nieuwe ronde"))
    {
        NewRound();
        GameNight.AnswerCommand(command.Id, true, "New round!");
    }
    else if (number.Success && text.Contains("orb"))
    {
        // Through the host, so every phone shows the new value too.
        GameNight.SetSetting("orbs", Clamp(int.Parse(number.Value, CultureInfo.InvariantCulture), 2, 16));
        GameNight.AnswerCommand(command.Id, true, $"{Clamp(int.Parse(number.Value, CultureInfo.InvariantCulture), 2, 16)} orbs.");
    }
    else if (number.Success && (text.Contains("second") || text.Contains("seconde") || text.Contains("round")))
    {
        GameNight.SetSetting("round_seconds", Clamp(int.Parse(number.Value, CultureInfo.InvariantCulture), 20, 180));
        GameNight.AnswerCommand(command.Id, true, "Next round lasts " + Clamp(int.Parse(number.Value, CultureInfo.InvariantCulture), 20, 180) + " seconds.");
    }
    else GameNight.AnswerCommand(command.Id, false, "Try \"8 orbs\", \"rounds of 90 seconds\" or \"new round\".");
    Trace("command " + command.Text);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Names, colours and faces

Every player arrives with a name, a clothing colour, a skin colour and their own pixel-art face. GameNightFaces.Head(player, size) paints the head every Splitscreen Club game draws, as a Texture2D, cached per face. Put it on a sprite, a quad or a RawImage; hair may stick out past the circle:

// The player's own face, from their GameNight profile. Bots get the default face.
var head = GameNightFaces.Head(r.Profile ?? new Player { Name = r.Name }, 64);
if (body.FaceTexture != head)
{
    body.FaceTexture = head;
    body.Face.sprite = Sprite.Create(head, new Rect(0, 0, head.width, head.height), new Vector2(0.5f, 0.5f), 40f);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushView.cs

PlayersUpdated fires when someone picks up a profile in the lobby mid-match: the same players in the same seats, with a new name, colour or face. Update in place and keep playing; never restart over it.

Lay out anything that runs left to right, such as split screens or a scoreboard, in couch order: where the players sit, which they pick in the lobby. Couch.Order(seats, players) sorts seats that way:

public List<Runner> CouchOrder()
{
    var seats = new List<Seat>();
    foreach (var r in Runners) seats.Add(new Seat { Index = r.Seat, PlayerId = r.Profile?.Id ?? "" });
    var ordered = Couch.Order(seats, GameNight.Players);
    var result = new List<Runner>();
    foreach (var seat in ordered) result.Add(Runners.Find(r => r.Seat == seat.Index && (r.Profile?.Id ?? "") == seat.PlayerId && !result.Contains(r)));
    result.RemoveAll(r => r == null);
    return result;
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Players joining and leaving

After NotifyParticipation, RosterChanged brings the new seats and players when someone joins or leaves during your session. Keep everyone else's score:

void OnRoster(IReadOnlyList<Seat> seats, IReadOnlyList<Player> players)
{
    var kept = new List<Runner>();
    foreach (var seat in seats)
    {
        if (!seat.IsPlayed) continue;
        var r = Runners.Find(x => x.Seat == seat.Index && x.Bot == seat.IsBot && (x.Bot || x.Profile?.Id == seat.PlayerId));
        if (r == null)
        {
            r = new Runner { Bot = seat.IsBot, Seat = seat.Index };
            Place(r, kept.Count, Math.Max(seats.Count, 1));
            Trace("joined seat " + seat.Index);
        }
        Dress(r, GameNight.PlayerForSeat(seat), kept.Count);
        kept.Add(r);
    }
    if (kept.Count == 0) return;
    Runners.Clear();
    Runners.AddRange(kept);
    if (MenuOwner >= Runners.Count) MenuOwner = -1;
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

Saved progress

SavePlayerData(playerId, data) stores any JSON value up to 64 KB with a player's profile: unlocks, stats, a best score. It arrives back through PlayerDataChanged and PlayerData(playerId). UnlockForPresent(item) adds an unlock for everyone here now, and PartyUnion() is what anyone here has unlocked, for tonight only:

void EndRound()
{
    Results = ResultsSeconds;
    Stats["rounds"]++;
    var winner = Ranking()[0];
    Trace($"round {Round} won by {winner.Name}");
    GameNight.AddRoomLog($"Round {Round}: {winner.Name} won with {winner.Score} orbs");
    // Saved progress: every player's best round, and wins.
    foreach (var r in Runners)
    {
        if (r.Profile == null) continue;
        var data = GameNight.PlayerData(r.Profile.Id) as Dictionary<string, object> ?? new Dictionary<string, object>();
        data["best"] = Math.Max((int)Json.Long(data, "best"), r.Score);
        if (r == winner) data["wins"] = Json.Long(data, "wins") + 1;
        GameNight.SavePlayerData(r.Profile.Id, data);
    }
    // The host keeps the session going: we show results, then the next round.
    if (!string.IsNullOrEmpty(Session)) GameNight.NotifyFinished(Session);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

AddRoomLog(text) adds a line to the room log players read back in the Splitscreen Club app, never on the TV. Use it for a round or a winner, not every frame.

Phone screens

A phone screen is a small web page every player gets on their phone. Keep it under Assets/StreamingAssets, which stays a real folder in a desktop build, and declare it from Connected with GameNight.DeclarePhoneScreen("phone"). The package checks the folder fits a hosted room. Orb Rush's page is StreamingAssets/phone/index.html: your score and a boost button. Messages from a phone are untrusted input:

void OnPhoneMessage(string playerId, object data)
{
    // Untrusted input: only act on what we expect.
    if (!(Json.Obj(data) is Dictionary<string, object> msg) || Json.Str(msg, "action") != "boost") return;
    var r = Runners.Find(x => x.Profile?.Id == playerId);
    if (r == null || r.Boost > 0f || HostPaused) return;
    r.Boost = BoostTime;
    Trace("boost " + r.Name);
    SendPhone(playerId);
}

void SendPhone(string playerId)
{
    var r = Runners.Find(x => x.Profile?.Id == playerId);
    if (r == null) return;
    GameNight.SendCompanionMessage(new Dictionary<string, object>
    {
        ["name"] = r.Name, ["color"] = r.Color, ["score"] = r.Score, ["round"] = Round, ["boosting"] = r.Boost > 0f,
    }, playerId);
}

Source: examples/unity-demo/Assets/OrbRush/OrbRushGame.cs

See Phone screens for the page side.

The screen

GameNightScreen comes with the package and needs no code. When Splitscreen Club launched the game it mutes and minimises the window at startup, drops to 10 frames a second once you report Ready, takes the screen in borderless fullscreen with sound on at Start and Resume, and gets out of the way on Pause and Dispose. Window focus never starts or resumes a game; only the host does. Set Automatic to false to call GoQuiet, Settle and TakeTheScreen yourself.

On Windows it minimises without taking focus and parks a warming window off screen; on macOS it hides the app. On Linux there is no portable way to hide a window, so it only mutes and throttles. Unity creates its window before any script runs, so a warming game may show for a moment at launch; starting windowed and without a splash screen keeps that short.

Test without Unity

The SDK core and Orb Rush's rules are plain C#, kept apart from the Unity view. CI builds them into a console game with dotnet and plays every feature on this page against a fake Splitscreen Club host, then compiles the Unity layer and the view against Unity's reference assemblies:

python3 scripts/test-unity-sdk.py
dotnet build "sdk/unity/Tests~/Harness" -c Release -o /tmp/orb-rush
cargo run -p gamenight-certify -- unity-demo -- /tmp/orb-rush/orb-rush-headless

Keep your own game split the same way and you can test it like this too. These checks do not run a Unity build: window handling, faces on screen and real pads need a test on hardware. Build the demo with Splitscreen Club → Build Orb Rush in the editor, then run the integration checks on the build.

After changing a file in sdk/unity, run python3 scripts/unity-package-meta.py: a package installed from git needs a .meta file next to every file, and CI checks they are there.