Docs/Unity Client API
API Reference

Unity Client API Reference

This is the complete reference for the TurnKit Unity client runtime API. Relay is the main entry point for matchmaking, gameplay actions, lists, stats, and voting. For package installation and project setup, start with the Unity Quickstart.

Getting Started

Before using Relay operations, authenticate the player and connect to a match. Identity setup differs by auth mode, so check Player Authentication Modes before wiring your login flow.

Connection Flow

// Authenticate and enter the match
// Option A: Development / Open (No verification)
await Relay.MatchWithAnyone(playerId, ExampleConfig.Slug);

// Option B: Standard Session (After OTP/Social Auth)
var session = new TurnKitPlayerSession(playerId, playerToken, email);
await Relay.MatchWithAnyone(session, ExampleConfig.Slug);

// Option C: Secure/Signed (External backend verification)
var signed = new TurnKitSignedPlayer(playerId, timestamp, nonce, signature);
await Relay.MatchWithAnyone(signed, ExampleConfig.Slug);
MethodDescription
await Relay.MatchWithAnyone(playerId, configSlug)Resolves the relay config, joins matchmaking, stores session state, and opens the WebSocket. Returns true on success.
await Relay.Reconnect()Retries the WebSocket connection using the last known session context.
await Relay.LeaveQueue(playerId, configSlug)Leaves the matchmaking queue and closes any active WebSocket.
For wire format, reconnect semantics, and server message shapes, pair this page with the WebSocket Protocol reference.

Core Relay Actions

These methods control move submission and match flow once the client is connected.

MethodDescription
Relay.SendJson(jsonString)Queues raw JSON to be included in the next move payload.
Relay.Commit()Sends all currently queued actions without ending your turn. Use for mid turn actions.
Relay.EndMyTurn()Sends queued actions and marks the move as ending your turn.
Relay.EndGame()Signals the server that the current match should end.
Relay.Vote(moveNumber, approved)Submits a vote on whether the specified move or variable change is valid. When voting is in SYNC mode, the server waits for votes from clients (as per config) before changing turn.

Lists & Items

Lists are the primary way to represent runtime state such as hands, decks, discard piles, and board zones.

Accessing Lists

var results = Relay.List(ExampleConfig.List.results_public);      // throws if not found
var publicList = Relay.GetList(ExampleConfig.List.results_public); // returns null if missing

var myHands = Relay.GetMyLists(ExampleConfig.Tag.hand);
var opponentHands = Relay.GetOpponentsLists(ExampleConfig.Tag.hand);

List Operations

// Spawn
list.Spawn("card_slug");
list.Spawn(customItemId, "card_slug");

// Move items
list.Move(SelectorType.TOP).To(targetList);
list.Move(SelectorType.BY_SLUGS, new[] { "king", "queen" })
    .Repeat(2)
    .IgnoreOwnership()
    .To(targetList);

// Remove and shuffle
list.Remove(SelectorType.ALL);
list.Remove(SelectorType.BY_ITEM_IDS, itemIds).Repeat(3);
list.Shuffle();

To

.To(targetList) completes and queues the move.

Repeat

.Repeat(count) repeats the move or remove operation.

IgnoreOwnership

.IgnoreOwnership() bypasses ownership checks, validate via voting.

Querying Items

list.FindById(itemId) returns the first matching item or null.

list.FindBySlug("card_slug") returns all items with that slug.

list.FindBySlugs("a", "b", "c") returns all items matching any provided slug.

Useful Properties

Reach for list.Count, list.Items, list.Top, list.Bottom, list.IsOwnedByMe, and list.IsVisibleToMe when rendering gameplay UI.

Stats & Leaderboards

Stats can be tracked per match or per player, and can feed directly into configured leaderboards. For the dedicated leaderboard module, continue to the Leaderboards docs. For webhook destinations and post-match routing, see Relay Stats & Leaderboards.

// Per-player stat
Relay.Stat(ExampleConfig.Stats.Score)
    .ForPlayer(Relay.MySlot)
    .Add(150);

// Simple stat updates
Relay.Stat(ExampleConfig.Stats.Status).Set("won");
Relay.Stat(ExampleConfig.Stats.Tags).Add("first_blood", "aggressive");

ForPlayer

.ForPlayer(slot) targets a specific player and is required for per-player stats.

Set

.Set(value) sets numeric, string, or string-list values.

Add

.Add(value) increments numeric stats or appends to string-list stats.

Direct Leaderboard Methods

MethodDescription
await Leaderboard.SubmitScore(playerId, score, metadata, leaderboardSlug)Submits a score manually.
await Leaderboard.GetTopScores(playerId, limit, leaderboardSlug)Returns top entries.
await Leaderboard.GetMyRank(playerId, surrounding, leaderboardSlug)Gets the current player's rank plus nearby entries.
await Leaderboard.GetCombined(playerId, topLimit, surrounding, leaderboardSlug)Returns top scores and the current player's rank in one call.
When automatic leaderboard scoring is enabled in your relay config, updates via Relay.Stat() can update the linked leaderboard automatically.

Player & Session

Authentication

await TurnKitAuth.RequestOtp(email);
var session = await TurnKitAuth.VerifyOtp(email, otp);

new TurnKitPlayerSession(playerId, token, email);
new TurnKitSignedPlayer(playerId, timestamp, nonce, signature);
signedPlayer.BuildSignaturePayload(); // returns the string to sign

Match State Properties

Relay.MyPlayerId, Relay.MySlot

Relay.IsMyTurn, Relay.IsReady

Relay.AllPlayers, Relay.GetPlayerBySlot(slot)

Relay.LastAcknowledgedMoveNumber

Helper & Utility Methods

typedStatChanges.TryGet(statToken, out var change) safely reads stat changes from messages.

matchStartedMessage.ToString(listCount) helps with debug formatting.

Relay.AllLists exposes a read-only view of initialized lists.

Error Handling & Best Practices

  • Relay.MatchWithAnyone() returns false instead of throwing on config or queue failures.
  • Action methods such as Commit, EndMyTurn, and Vote become no-ops when the WebSocket is disconnected.
  • Prefer generated config enums like ExampleConfig.List.xxx and ExampleConfig.Stats.xxx over raw strings.
  • Complex list operations are safest and clearest when you use the fluent builder pattern.
  • Combine Relay with post-match webhooks for backend workflows, rewards, or verified leaderboard submission after each match.

Main Source Files

Assets/TurnKit/Runtime/Relay/Relay.cs

Assets/TurnKit/Runtime/Relay/RelayList.cs

Assets/TurnKit/Runtime/Relay/RelayStat.cs

Assets/TurnKit/Runtime/Leaderboard/Leaderboard.cs

Assets/TurnKit/Runtime/Core/TurnKitAuth.cs

Unity Client API Reference - TurnKit Docs