Skip to article Developer portalAdd your game

SPLITSCREEN CLUB / DOCUMENTATION

Unreal Engine

The Splitscreen Club plugin for Unreal Engine 5 lives in sdk/unreal/GameNight. It covers the whole game contract: the connection and lifecycle, input per seat, the window and audio, the world pause, match and per-player settings, saved progress, faces and phone screens. Dash Derby in examples/unreal-demo is a complete demo game built on it, and every snippet on this page comes from that game or the plugin.

The plugin is written for Unreal Engine 5.3 and later on Windows, macOS and Linux. Its protocol core is plain C++17 and runs in CI on every change; the Unreal side has no Unreal build in CI yet. See What is tested.

Add the plugin

Copy sdk/unreal/GameNight into your project's Plugins/ folder, or point your .uproject at the folder that holds it, as the demo does:

{
	"FileVersion": 3,
	"EngineAssociation": "5.8",
	"Category": "",
	"Description": "Dash Derby: the GameNight demo game for Unreal Engine.",
	"Modules": [
		{
			"Name": "DashDerby",
			"Type": "Runtime",
			"LoadingPhase": "Default",
			"AdditionalDependencies": [ "Engine" ]
		}
	],
	"Plugins": [
		{ "Name": "GameNight", "Enabled": true }
	],
	"AdditionalPluginDirectories": [ "../../sdk/unreal" ]
}

Source: examples/unreal-demo/DashDerby.uproject

Add "GameNight" to your module's dependencies in its .Build.cs, then set your game id under Project Settings > Plugins > Splitscreen Club. It must match your catalog entry; Splitscreen Club also passes it in GAMENIGHT_GAME_ID.

[/Script/GameNight.GameNightSettings]
GameId=unreal-demo
bAutomaticScreen=True
bPauseWorldWhenNotRunning=True
WarmMaxFPS=10

Source: examples/unreal-demo/Config/DefaultGame.ini

A game started by hand stays offline, so a test run never joins the party on your machine. Turn on Connect Standalone (or set GAMENIGHT_ADDR) to connect a Play In Editor session to a running Splitscreen Club.

How it fits together

Everything goes through UGameNightSubsystem, a game instance subsystem that lives from boot to quit and ticks also while the game is paused. Get it from any actor with UGameNightSubsystem::Get(this), or in Blueprint with the Splitscreen Club Subsystem node. It talks to Splitscreen Club over the plain TCP transport (one JSON message per line) on the same port as the WebSocket one.

The contract is the same as in every SDK:

  1. OnPrepared: build the level for GetSeats() and GetPlayers() while hidden, then call NotifyReady(). Show nothing yet.
  2. OnStarted: you are on screen. Start the match at once.
  3. OnPaused and OnResumed: the party went to the lobby and came back.
  4. A round ends: call NotifyFinished(), show the results, play the next round. Rounds repeat until the party picks another game.
  5. OnDisposed: tear the session down. Another OnPrepared may follow.

The plugin takes care of the window and sound on its own: muted and off the screen while warming, a lower frame cap once ready, borderless fullscreen in front on Start and Resume, and away again on Pause. It also pauses the world whenever the session is not running, so physics, timers and game sounds stop without code from you. Both are settings. F1 returns to the party; the controller's Back button is Splitscreen Club's own and reaches the host directly. When the host goes away, a launched game quits.

Bind the lifecycle

Dash Derby connects its handlers in BeginPlay and declares its settings, its phone button and its phone screen once. The plugin declares them again after every reconnect.

UGameNightSubsystem* GN = GameNight();
if (GN && GN->IsLaunchedByGameNight())
{
	GN->OnConnected.AddDynamic(this, &ADashDerbyGameMode::HandleConnected);
	GN->OnPrepared.AddDynamic(this, &ADashDerbyGameMode::HandlePrepared);
	GN->OnStarted.AddDynamic(this, &ADashDerbyGameMode::HandleStarted);
	GN->OnPaused.AddDynamic(this, &ADashDerbyGameMode::HandlePaused);
	GN->OnResumed.AddDynamic(this, &ADashDerbyGameMode::HandleResumed);
	GN->OnDisposed.AddDynamic(this, &ADashDerbyGameMode::HandleDisposed);
	GN->OnRosterChanged.AddDynamic(this, &ADashDerbyGameMode::HandleRosterChanged);
	GN->OnPlayersUpdated.AddDynamic(this, &ADashDerbyGameMode::HandlePlayersUpdated);
	GN->OnSettingChanged.AddDynamic(this, &ADashDerbyGameMode::HandleSettingChanged);
	GN->OnPlayerSettingsChanged.AddDynamic(this, &ADashDerbyGameMode::HandlePlayerSettings);
	GN->OnActionTriggered.AddDynamic(this, &ADashDerbyGameMode::HandleAction);
	GN->OnCompanionMessage.AddDynamic(this, &ADashDerbyGameMode::HandlePhone);
	GN->OnCompanionPresence.AddDynamic(this, &ADashDerbyGameMode::HandlePhonePresence);
	// Declared once; the plugin declares them again after a reconnect.
	GN->DeclareSettings(SettingsSpec());
	GN->DeclareActions(ActionsSpec());
	GN->DeclareCompanionFolder(TEXT("Phone"), TEXT("index.html"));
	bHostPaused = true;
	Trace(TEXT("waiting for prepare"));
	// GameNight may have prepared us while the map was still loading.
	if (GN->GetPhase() != EGameNightPhase::Idle) HandlePrepared(GN->GetSessionId());
	if (GN->GetPhase() == EGameNightPhase::Running) HandleStarted(GN->GetSessionId());
	return;
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

On prepare, it seats everyone in couch order (left to right as they sit), opts into live joins and reports ready:

void ADashDerbyGameMode::HandlePrepared(const FString& SessionId)
{
	UGameNightSubsystem* GN = GameNight();
	GN->NotifyProgress(20, TEXT("seating players"));
	SeatFromSession();
	NewRound();
	bHostPaused = true;
	// Live roster: players who join mid-round get a runner at once.
	GN->NotifyParticipation(true);
	GN->NotifyProgress(100, TEXT("ready"));
	// The level exists and the first frame can be drawn: ready, still hidden.
	GN->NotifyReady();
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

void ADashDerbyGameMode::SeatFromSession()
{
	UGameNightSubsystem* GN = GameNight();
	ClearRunners();
	for (const FGameNightSeat& Seat : GN->GetCouchOrder())
	{
		FOrbRunner Runner;
		Runner.Seat = Seat.Index;
		if (Seat.Occupant == EGameNightOccupant::AI)
		{
			Runner.bBot = true;
		}
		else if (Seat.Occupant == EGameNightOccupant::Local || Seat.Occupant == EGameNightOccupant::Remote)
		{
			GN->GetPlayer(Seat.PlayerId, Runner.Player);
		}
		else
		{
			continue;
		}
		AddRunner(MoveTemp(Runner));
	}
	if (Runners.Num() == 0)
	{
		FOrbRunner Bot;
		Bot.bBot = true;
		AddRunner(MoveTemp(Bot));
	}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

Seats with an AI occupant get a bot. Empty seats are skipped. The number of people is LocalSeatCount(), never the number of pads you can see.

Read input per seat

Splitscreen Club routes every controller and phone to a seat. Read the seat, never local device order: GetPad(Seat) gives the sticks (deadzone applied, up is negative Y as on the wire) and buttons, and JustPressed(Seat, Button) is true on the frame a button went down. A button still held from the lobby must be released first, so one press never does two things.

if (Runner.Seat >= 0)
{
	// GameNight input: this seat's controller, whichever device it is.
	UGameNightSubsystem* GN = GameNight();
	const FGameNightPad Pad = GN->GetPad(Runner.Seat, true);
	Move = Pad.LeftStick;
	for (const EGameNightButton Button : {EGameNightButton::A, EGameNightButton::B, EGameNightButton::Start,
	                                      EGameNightButton::Up, EGameNightButton::Down, EGameNightButton::Left,
	                                      EGameNightButton::Right})
	{
		if (GN->JustPressed(Runner.Seat, Button)) OutPressed |= Bit(Button);
	}
	if (Pad.Buttons != 0 || !Move.IsNearlyZero(0.3)) GN->ReportActivity(Runner.Seat);
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

ReportActivity tells Splitscreen Club someone is really playing, so the party does not mark them asleep. Rumble(Seat, Weak, Strong, Seconds) vibrates that seat's controller. Back is never bound: it returns to the party.

Players, colours and faces

FGameNightPlayer carries the name, the clothing Color, the SkinColor and the drawn face. Use the colour for the player's body and draw the head with DrawFace on a HUD canvas. It draws the skin circle and the face, or the default face when the player has none, and mirrors it with Facing = -1.

// Each player's own face rides above their body.
for (const FOrbRunner& Runner : Mode->Runners)
{
	const FVector Screen = Project(Mode->BodyLocation(Runner) + FVector(0.0, 0.0, 95.0));
	if (Screen.Z <= 0.0) continue;
	const float Facing = Runner.Velocity.X < -1.0 ? -1.0f : 1.0f;
	GN->DrawFace(Canvas, Runner.Player, FVector2D(Screen.X, Screen.Y), 30.0f * Unit, Facing);
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyHUD.cpp

GetFaceTexture(Player) gives the face alone as a nearest-filtered texture, for a material or a widget. Profile changes arrive in OnPlayersUpdated while the match runs: update in place and never restart.

void ADashDerbyGameMode::HandlePlayersUpdated()
{
	// A name, colour or face changed. Update in place; never restart.
	UGameNightSubsystem* GN = GameNight();
	for (FOrbRunner& Runner : Runners)
	{
		if (Runner.Player.Id.IsEmpty()) continue;
		GN->GetPlayer(Runner.Player.Id, Runner.Player);
		ApplyShape(Runner);
		SendPhoneView(Runner);
	}
	Trace(TEXT("players updated"));
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

With NotifyParticipation(true), players who join or leave mid-round arrive in OnRosterChanged. Dash Derby keeps everyone still seated, with their score, and adds the newcomers at once.

Settings and the Start menu

Declare the settings the party may change. Phones, an LLM and your own menu change the same values; every change arrives in OnSettingChanged, also the ones you make yourself. A setting with "scope": "player" is every player's own choice, here the shape of their body.

// Declared to GameNight: the phones, an LLM and the Start menu change them.
Json SettingsSpec()
{
	Json Settings = Json::MakeArray();
	Settings.push(Json::MakeObject().set("key", "round_seconds").set("label", "Round length (seconds)").set("kind", "number")
	                  .set("default", 60).set("min", 20).set("max", 180));
	Settings.push(Json::MakeObject().set("key", "orbs").set("label", "Orbs on the field").set("kind", "number")
	                  .set("default", 6).set("min", 2).set("max", 16));
	Settings.push(Json::MakeObject().set("key", "bumps").set("label", "Dashes knock players away").set("kind", "toggle")
	                  .set("default", true));
	// "scope": "player": every player picks their own, on their phone.
	Settings.push(Json::MakeObject().set("key", "shape").set("label", "Your shape").set("kind", "choice")
	                  .set("default", "ball").set("options", Json::MakeArray().push("ball").push("cube").push("cone"))
	                  .set("scope", "player"));
	return Settings;
}

Json ActionsSpec()
{
	return Json::MakeArray().push(Json::MakeObject()
	                                  .set("key", "new_round")
	                                  .set("label", "New round")
	                                  .set("description", "Ends this round for everyone.")
	                                  .set("confirm", true));
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

Every Splitscreen Club Start menu has the same layout: the game's name, Resume, New round, then the settings, with no button hints. Dash Derby's menu sends each change back with SetSettingJson, so the phones show the same value:

ApplySetting(Key, Value);
	// Tell GameNight, so the phones and an LLM show the same value.
	UGameNightSubsystem* GN = GameNight();
	if (GN && GN->IsLaunchedByGameNight()) GN->SetSettingJson(Key, Value);
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

Rounds, results and saves

A round ends with NotifyFinished(); the session goes on. AddRoomLog writes one short line to the room log in the app. Each player's own progress is saved with their profile between nights, and UnlockForPresent gives an unlock to everyone who was there; PartyUnion reads what the people here tonight have.

void ADashDerbyGameMode::EndRound()
{
	Results = ResultsSeconds;
	TArray<const FOrbRunner*> Ranking;
	for (const FOrbRunner& Runner : Runners) Ranking.Add(&Runner);
	Ranking.StableSort([](const FOrbRunner& A, const FOrbRunner& B) { return A.Score > B.Score; });
	const FOrbRunner& Winner = *Ranking[0];
	Trace(FString::Printf(TEXT("round %d won by %s"), Round, *Winner.Player.Name));
	UGameNightSubsystem* GN = GameNight();
	if (GN && GN->IsLaunchedByGameNight())
	{
		// The session goes on: results now, then the next round, until the
		// party picks another game.
		GN->NotifyFinished();
		GN->AddRoomLog(FString::Printf(TEXT("%s won round %d with %d orbs"), *Winner.Player.Name, Round, Winner.Score));
		SaveProgress();
		// What the group earns counts for everyone who was there.
		if (Winner.Score >= 10) GN->UnlockForPresent(TEXT("crown"));
	}
	SendPhoneViews();
}

void ADashDerbyGameMode::SaveProgress()
{
	// Each player's own progress, kept with their profile between nights.
	UGameNightSubsystem* GN = GameNight();
	for (const FOrbRunner& Runner : Runners)
	{
		if (Runner.Player.Id.IsEmpty() || Runner.bBot) continue;
		const std::string Id = UGameNightSubsystem::ToUtf8(Runner.Player.Id);
		Json Data = GN->Core().player_data(Id);
		if (!Data.is_object()) Data = Json::MakeObject();
		Data.set("best", FMath::Max(static_cast<int64>(Data["best"].integer()), static_cast<int64>(Runner.Score)));
		Data.set("orbs", Data["orbs"].integer() + Runner.Score);
		Data.set("rounds", Data["rounds"].integer() + 1);
		GN->Core().SavePlayerData(Id, Data);
	}
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

The C++ API takes gamenight::Json values (GN->Core() is the protocol client underneath). Blueprints use the ...Json functions, which take and return JSON text.

Phone screens and phone buttons

DeclareActions puts buttons such as New round on every player's phone; presses arrive in OnActionTriggered. A phone screen is a small web page in Content/Phone, declared with DeclareCompanionFolder. The host serves it from a real folder, so stage it as loose files:

[/Script/UnrealEd.ProjectPackagingSettings]
; The phone screen must stay loose files the host can serve.
+DirectoriesToAlwaysStageAsNonUFS=(Path="Phone")
; Meshes and the map are referenced from code only, so cook them explicitly.
+DirectoriesToAlwaysCook=(Path="/Engine/BasicShapes")
+MapsToCook=(FilePath="/Engine/Maps/Entry")

Source: examples/unreal-demo/Config/DefaultGame.ini

The game decides and the phone draws: Dash Derby sends each player their whole view, again whenever their phone connects, and checks every tap against the rules.

void ADashDerbyGameMode::HandlePhone(const FString& PlayerId, const FString& DataJson)
{
	// Phone messages are untrusted input: check them against the rules.
	const Json Data = Json::parse(UGameNightSubsystem::ToUtf8(DataJson));
	if (Data["tap"].str() != "boost") return;
	for (FOrbRunner& Runner : Runners)
	{
		if (Runner.Player.Id != PlayerId || Runner.BoostCooldown > 0.0f || bHostPaused) continue;
		Runner.Boost = BoostTime;
		Runner.BoostCooldown = BoostCooldownTime;
		Trace(TEXT("boost ") + Runner.Player.Name);
		SendPhoneView(Runner);
	}
}

void ADashDerbyGameMode::HandlePhonePresence(const FString& PlayerId, bool bConnected)
{
	// Phones reload and sleep: send the whole view again on connect.
	for (FOrbRunner& Runner : Runners)
	{
		if (Runner.Player.Id != PlayerId) continue;
		Runner.bPhone = bConnected;
		if (bConnected) SendPhoneView(Runner);
	}
}

void ADashDerbyGameMode::SendPhoneView(const FOrbRunner& Runner)
{
	UGameNightSubsystem* GN = GameNight();
	if (!GN || Runner.Player.Id.IsEmpty()) return;
	// The game decides, the phone draws: send the view, not the history.
	Json View = Json::MakeObject();
	View.set("name", ToJson(Runner.Player.Name))
	    .set("color", ToJson(Hex(Runner.Player.Color)))
	    .set("score", Runner.Score)
	    .set("round", Round)
	    .set("clock", FMath::CeilToInt(FMath::Max(Clock, 0.0f)))
	    .set("results", Results > 0.0f)
	    .set("boost", Runner.BoostCooldown <= 0.0f);
	GN->SendCompanionMessage(View, Runner.Player.Id);
}

Source: examples/unreal-demo/Source/DashDerby/DashDerbyGameMode.cpp

The page itself is plain HTML with the host's /assets/companion.js; see Phone screens for the limits of hosted rooms.

<script src="/assets/companion.js"></script>
<script>
  // The game decides, the phone draws: every message is this player's whole view.
  const $ = (id) => document.getElementById(id);
  const game = GameNight.connect(render, (status) => {
    $("status").textContent = status === "connected" ? "" : "Reconnecting";
  });
  function render(view) {
    if (typeof view !== "object" || view === null) return;
    if (typeof view.color === "string") document.documentElement.style.setProperty("--you", view.color);
    $("name").textContent = view.name || "Dash Derby";
    $("score").textContent = String(view.score ?? 0);
    $("clock").textContent = view.results ? "Results" : (view.clock != null ? view.clock + " s" : "");
    $("boost").disabled = !view.boost || view.results;
  }
  $("boost").addEventListener("click", () => {
    $("boost").disabled = true;
    game.send({ tap: "boost" });
  });
</script>

Source: examples/unreal-demo/Content/Phone/index.html

Build and package

Open examples/unreal-demo/DashDerby.uproject with Unreal Engine 5.3 or later and let it build the modules, or build from the command line:

# Windows
Engine\Build\BatchFiles\RunUAT.bat BuildCookRun -project=<path>\DashDerby.uproject -platform=Win64 -clientconfig=Shipping -build -cook -stage -pak -archive -archivedirectory=<out>
# macOS
Engine/Build/BatchFiles/RunUAT.sh BuildCookRun -project=<path>/DashDerby.uproject -platform=Mac -clientconfig=Shipping -build -cook -stage -pak -archive -archivedirectory=<out>

The demo has no .umap and no assets of its own: it builds the arena from engine shapes in code, so it cooks /Engine/BasicShapes and the empty /Engine/Maps/Entry explicitly. Standalone, it plays with the keyboard (WASD, Space to dash, Escape for the menu) or the first pad against bots; pass -players=2 for more local players and -seed=7 for a repeatable game.

On Windows, Splitscreen Club starts games hidden. The plugin keeps a warming game minimised and muted until Start, and parks the window off the screen when the window server refuses to minimise it.

What is tested