---
title: "Unity and Godot · PlayerTwo"
url: https://playertwo.plus/docs/sdk/engines
description: "PlayerTwo's game SDK from C# in a Unity WebGL build and from GDScript in a Godot 4 web export: trophies, leaderboards, stats, cloud saves, the store, rooms and the rest for a game hosted on PlayerTwo (playertwo.plus), every call with an example."
source: PlayerTwo (https://playertwo.plus), made from the page itself
---

Documentation · Game SDK · Unity and Godot

# Unity and Godot

A Unity WebGL build or a Godot 4 web export hosted on PlayerTwo has [the game SDK](https://playertwo.plus/docs/sdk) in its page already. PlayerTwo’s plugin for Unity and add-on for Godot let your C# or GDScript call it: the player, trophies, stats, leaderboards, cloud saves, the store, rooms and the rest, each call with the same rules and answers as in JavaScript. Download [the Unity plugin](https://playertwo.plus/sdk/playertwo-unity.zip) or [the Godot add-on](https://playertwo.plus/sdk/playertwo-godot.zip).

1. **Your C# or GDScript asks** `P2.Trophies.Unlock("first-win")` or `P2.trophies_unlock("first-win")`.
2. **The bridge calls the SDK** In your game's page, as JSON: the same SDK, the same play session, never the player's sign-in.
3. **Your game hears the answer** In a callback (Unity, in Update) or an await (Godot): its data, or why it was refused.

## Unity WebGL

### Putting it in

- **Unity 2021.3 or later**, Unity 6 included, building for WebGL.
- Unzip [playertwo-unity.zip](https://playertwo.plus/sdk/playertwo-unity.zip) into your project’s folder: `Assets/Plugins/WebGL/PlayerTwo.jslib` (the browser half) and `Assets/PlayerTwo/P2.cs` and `P2Runner.cs` (the C# half). Or take the files one by one: [PlayerTwo.jslib](https://playertwo.plus/sdk/unity/PlayerTwo.jslib), [P2.cs](https://playertwo.plus/sdk/unity/P2.cs), [P2Runner.cs](https://playertwo.plus/sdk/unity/P2Runner.cs).
- Nothing to add to a scene, no template to change: PlayerTwo puts the SDK in your build’s page when it hosts it ([hosting](https://playertwo.plus/docs/hosting#engines-unity)). Everything is in the namespace `PlayerTwoSdk`; it uses no reflection, so any code stripping level works.

### Starting

Call `P2.Init` once, early. Every other call waits for it (one made before it starts PlayerTwo with no options).

C#

```
using PlayerTwoSdk;
using UnityEngine;

public class Boot : MonoBehaviour
{
    void Start()
    {
        P2.Init(r =>
        {
            if (!r.Ok) { Debug.Log("Playing without PlayerTwo: " + r.Code); return; }  // "not-on-player-two"
            Debug.Log("Hello " + P2.Player.Name + ", level " + P2.Player.Level);  // P2.Env: "p2" or "local"
            P2.Loading.Done();
        });
        P2.OnOverlay += open => Time.timeScale = open ? 0 : 1;   // PlayerTwo's layer over the game
        P2.OnFlush += () => P2.Saves.Put("slot-1", JsonUtility.ToJson(state));  // closing: waited for
    }
}
```

Every call answers once, by its callback, with a `P2Result`: `Ok` and `Data`, the SDK’s own answer as JSON (`r["rank"].Int`, `r.Data["trophy"]["name"].Str`; a key that isn’t there reads as null, never throws), or, refused, `Code`, `Message` and `Status`, with what else the refusal carries in `Data`. `r.Json` is the answer as text, for `JsonUtility.FromJson`. Callbacks run in `Update`, on the main thread, before your own scripts’ `Update`, never inside the call that asked; `P2.Async` makes any call a `Task`. In the Unity editor, and in any build but WebGL, every call answers `not-on-player-two`.

C#: the calls you'll use most

```
P2.Trophies.Unlock("first-win");                              // the player sees the toast
P2.Stats.Add("duels-won", 1);                                  // a trophy waiting on a stat is earned by itself
P2.Scores.Submit("time-attack", 83.4, r => Debug.Log("Rank " + r["rank"].Int + " of " + r["total"].Int));

P2.Saves.Get("slot-1", r => { if (r.Ok) state = JsonUtility.FromJson<State>(r.SaveText()); });
P2.Saves.Put("slot-1", JsonUtility.ToJson(state), r =>
{
    if (r.Code == "version") Debug.Log("Another device saved: version " + r["version"].Int);
}, version: 3);

P2.Store.Buy("blaze-ball", r =>
{
    if (r.Ok && r["ok"].Bool) Equip(r["product"]["key"].Str);   // r["receipt"].Str: signed, for your server
    else if (r.Ok) Debug.Log("Not now");                          // { ok: false, reason: "cancelled" }
    else Debug.Log(r.Code);                                       // "no-store", "guest", "owned", ...
});

var unlocked = await P2.Async(cb => P2.Trophies.Unlock("flawless-duel", cb));   // or as a Task
```

### Every call

_The SDK from C#_

| What | C# | Answers |
| --- | --- | --- |
| [Start](https://playertwo.plus/docs/sdk#call-init) | `P2.Init(r => ...)` | Who is playing: `P2.Player`, the game, test, demo, guest, params, env. Options: Timeout, Required, Local, Sdk. |
| [Who is playing](https://playertwo.plus/docs/sdk#call-me) | `P2.Me(r => ...)` | `{ player, game, session, test, demo, from, params }` |
| [Identity for your servers](https://playertwo.plus/docs/sdk#call-identity) | `P2.Identity(r => Send(r.Data.Str))` | A JWT signed by PlayerTwo, ten minutes. |
| [An invite link](https://playertwo.plus/docs/sdk#call-identity) | `P2.Invite(new Dictionary<string, string> { { "room", id } }, r => ...)` | A link that opens your game with these params. |
| [The avatar](https://playertwo.plus/docs/sdk/travel#avatar) | `P2.Avatar(r => ...)` | The critter's pixels and 3D model, name, level, what they wear. |
| [Their shop items](https://playertwo.plus/docs/sdk/travel#avatar-items) | `P2.Items.List(r => ...)` | `[{ key, name, kind, tier, slot, worn, ... }]` |
| [Ask a guest to sign up](https://playertwo.plus/docs/sdk#sign-up) | `P2.SignUp("To buy the Gold Pack")` | `{ ok, card? } or { ok: false, reason }` |
| [Trophies](https://playertwo.plus/docs/sdk#call-trophies) | `P2.Trophies.List(r => ...)` | `{ trophies, xp, level }` |
| [Earn a trophy](https://playertwo.plus/docs/sdk#call-trophies) | `P2.Trophies.Unlock("first-win")` | `{ trophy, new, n, xp, level, complete? }` |
| [Add-ons](https://playertwo.plus/docs/sdk#addons) | `P2.Addons.List(r => ...) · P2.Addons.Has("night-map", r => ...)` | Each on sale; whether the player has one (data is true or false). |
| [The store](https://playertwo.plus/docs/sdk#store) | `P2.Store.List(r => ...) · P2.Store.Owned(r => ...)` | Your products (coming: true lists those ahead too); what the player has. |
| [Who may buy](https://playertwo.plus/docs/sdk#store-access) | `P2.Store.Access(r => ...)` | `{ state, until, left?, via? }` |
| [Charges sold](https://playertwo.plus/docs/sdk#store-counts) | `P2.Store.Sold(new[] { "s1:*" }, r => ...)` | `{ "s1:*": 40 }` |
| [Buy](https://playertwo.plus/docs/sdk#store) | `P2.Store.Buy("blaze-ball", r => ...)` | PlayerTwo’s own sheet; `{ ok, product, receipt, ... }`. |
| [Pay a charge](https://playertwo.plus/docs/sdk#store-charges) | `P2.Store.Pay(chargeId, r => ...)` | `{ ok, charge, amount, receipt, ... }` |
| [The shop screen](https://playertwo.plus/docs/sdk#store-shop) | `P2.Store.Open(r => ..., kind: "skin")` | PlayerTwo’s own shop over the game; when it closes, `{ ok, bought: [...] }`. |
| [Try-on](https://playertwo.plus/docs/sdk#store-shop) | `P2.Store.TryOn() · P2.OnTryOn += item => ...` | The product the player looks at in the shop screen, then null. |
| [The daily deal](https://playertwo.plus/docs/sdk#store-deal) | `P2.Store.Deal(r => ...)` | `{ product, percent, price, was, ends } or null` |
| [Donations](https://playertwo.plus/docs/sdk#donate) | `P2.Donate.Available(r => ...) · P2.Donate.Open()` | Whether they're on; PlayerTwo's sheet, from the player's press. |
| [The Donate button](https://playertwo.plus/docs/sdk#donate) | `P2.Donate.Button("bottom-right") · P2.Donate.RemoveButton()` | `{ shown } · { removed }` |
| [Moments](https://playertwo.plus/docs/sdk#moments) | `P2.Moments.Offer()` | `{ offered, shared }` |
| [Notifications](https://playertwo.plus/docs/sdk#notify) | `P2.Notify.Ask("to tell you when your crops are ready", r => ...) · P2.Notify.Allowed(r => ...)` | `{ allowed, asked } · true or false` |
| [The device](https://playertwo.plus/docs/sdk#device) | `P2.Device.Get(r => ...)` | `{ tier, phone, touch, memory, cores, gpu, fps, ... }` |
| [Stats](https://playertwo.plus/docs/sdk#call-stats) | `P2.Stats.All(r => ...) · P2.Stats.Get("kills", r => ...)` | Every stat, or one (a number). |
| [Change a stat](https://playertwo.plus/docs/sdk#call-stats) | `P2.Stats.Set("kills", 9) · P2.Stats.Add("kills", 1)` | `{ stats, unlocked }` |
| [Leaderboards](https://playertwo.plus/docs/sdk#call-scores) | `P2.Scores.Submit("time-attack", 83.4) · P2.Scores.List("time-attack", r => ..., "me")` | `{ rank, total, best, ... } · { rows, total, me }` |
| [Saves](https://playertwo.plus/docs/sdk#call-saves) | `P2.Saves.List(r => ...) · P2.Saves.Get("slot-1", r => r.SaveText())` | Slots; a save’s text (or `r.SaveBytes()`, `P2.save_bytes(result)`). |
| [Keep a save](https://playertwo.plus/docs/sdk#call-saves) | `P2.Saves.Put("slot-1", text, version: 3) · P2.Saves.Delete("slot-1")` | Text or bytes (and in GDScript a Dictionary as JSON), up to 1 MB. |
| [Presence](https://playertwo.plus/docs/sdk#call-presence) | `P2.Presence.Set("Chapter 3", join)` | The line friends see; join: what they join you with. |
| [Loading and play](https://playertwo.plus/docs/sdk#call-gameplay) | `P2.Loading.Done() · P2.Gameplay.Start() · P2.Gameplay.Stop()` | For your studio's analytics. |
| [Your own events](https://playertwo.plus/docs/sdk#call-track) | `P2.Track("level_start", new Dictionary<string, object> { { "level", 3 } })` | Fire and forget. |
| [Your errors](https://playertwo.plus/docs/sdk#call-crashes) | `P2.Errors.Report(message, "Boss", stack) · P2.Errors.CatchExceptions() · P2.Errors.Off()` | Fire and forget; CatchExceptions reports every exception Unity logs. |
| [Feeds](https://playertwo.plus/docs/sdk#feeds) | `P2.Feeds.Get("x-posts", r => ...)` | `{ at, status, body } or { at, items }` |
| [Travel](https://playertwo.plus/docs/sdk/travel#travel) | `P2.Travel.To("hoop-it") · P2.Travel.Home() · P2.Travel.Links(r => ...)` | Doors to other games, the party with them. |
| [The party](https://playertwo.plus/docs/sdk/travel#party-play) | `P2.Party.Get(r => ...) · P2.Party.Lead() · P2.OnLead += lead => ...` | The party, its leader's pick now, and as it changes. |
| [The overlay and closing](https://playertwo.plus/docs/sdk#call-overlay) | `P2.OnOverlay += open => ... · P2.OnFlush += () => ...` | Pause; keep what must last (calls made then are waited for). |
| [Any call by its name](https://playertwo.plus/docs/sdk#call-init) | `P2.Call("trophies.list", new object[0], r => ...)` | What these files don't wrap yet. |

### Rooms

Each way into a room answers `r.Room`, a `P2Room`: its `Id`, `Code`, `Mode`, `Size`, `Me`, `Scripted` and `Open`, and its events as C# events: `OnJoin`, `OnLeave`, `OnAway`, `OnBack`, `OnHost`, `OnTeam`, `OnState`, `OnMessage`, `OnReconnecting`, `OnReconnected`, `OnMoved`, `OnVoice`, `OnSpeaking`, `OnAlone`, `OnError`, `OnClose`, `OnSyncJoin`, `OnSyncLeave`, `OnSyncFix`, `OnObjectAdd`, `OnObjectRemove`.

C#: a duel with smooth movement

```
P2.Rooms.Join(new P2RoomOptions { Mode = "duel", Size = 2 }, r =>
{
    if (!r.Ok) return;
    room = r.Room;
    room.OnJoin += p => Debug.Log(p["name"].Str + " came in");
    room.OnMessage += (type, data, from) => { if (type == "hit") TakeHit(data["damage"].Int); };
    room.OnState += (key, value, by) => Debug.Log(key + " = " + value);
    room.OnSyncJoin += (id, values) => others[id] = Instantiate(ghost);
    room.OnClose += why => Debug.Log("Out: " + why);
    room.SyncStart(new[] { "x", "y", "z", "ry" });
});

void Update()
{
    if (room == null || !room.Open) return;
    var me = player.transform;
    var them = room.SyncStep(me.position.x, me.position.y, me.position.z, me.eulerAngles.y * Mathf.Deg2Rad);
    foreach (var id in them.Keys)
    {
        var v = them[id];   // smoothed: [x, y, z, ry]
        if (others.TryGetValue(id, out var o)) o.transform.position = new Vector3(v[0].Float, v[1].Float, v[2].Float);
    }
    if (Input.GetKeyDown(KeyCode.Space)) room.Send("hit", new Dictionary<string, object> { { "damage", 12 } });
}
```

_Rooms from C#_

| What | C# |
| --- | --- |
| [Join a match, a code or your room](https://playertwo.plus/docs/sdk#rooms-join) | `P2.Rooms.Join(new P2RoomOptions { Mode = "duel", Size = 2 }, r => room = r.Room)` |
| [A private room, the party's](https://playertwo.plus/docs/sdk#rooms-join) | `P2.Rooms.Create(options, cb) · P2.Rooms.Party(options, cb)` |
| [A world, watching, what's live](https://playertwo.plus/docs/sdk#rooms-worlds) | `P2.Rooms.World("main", cb, "docks") · P2.Rooms.Watch(id, cb) · P2.Rooms.Live("duel", cb)` |
| [A bad line, on purpose](https://playertwo.plus/docs/sdk#rooms-simulate) | `P2.Rooms.Simulate(150, 30, 0.02) · P2.Rooms.StopSimulating()` |
| [Who, what, the host](https://playertwo.plus/docs/sdk#rooms-talk) | `room.Info() · room.Players · room.State · room.Host · room.IsHost · room.Get("round")` |
| [Messages and shared state](https://playertwo.plus/docs/sdk#rooms-talk) | `room.Send("hit", data) · room.SendTo("hit", data, ids) · room.Set("round", 3)` |
| [Time and the line](https://playertwo.plus/docs/sdk#rooms-fast) | `room.Ping(r => ...) · room.Now() · room.Stats()` |
| [Smooth movement](https://playertwo.plus/docs/sdk#rooms-sync) | `room.SyncStart(fields) · room.SyncStep(x, y, z, ry) · room.SyncStop()` |
| [The room code's objects](https://playertwo.plus/docs/sdk#rooms-objects) | `room.ObjectsStart() · room.ObjectsStep() · room.ObjectsStop()` |
| [Voice chat](https://playertwo.plus/docs/sdk#rooms-voice) | `room.VoiceJoin() · room.VoiceMute() · room.VoiceVolume(id, 0.5) · room.VoiceLeave()` |
| [Leave](https://playertwo.plus/docs/sdk#rooms-join) | `room.Leave()` |

**Smooth movement:** name your numbers once, then hand `room.SyncStep` yours every frame: they go out at the sync’s rate, and every other player’s come back smoothed, by id. A scripted room’s correction comes as `OnSyncFix` with the values to put your player at. A room’s data is anything JSON carries: a `Dictionary`, a list, a number, a string, or `P2Json.Parse(JsonUtility.ToJson(x))`.

### Limits

- **No C# threads in WebGL.** Callbacks run on the main thread; `await` on `P2.Async` goes on there too. `Task.Run` and `System.Threading` don’t run in a browser.
- **Sound** is the browser’s Web Audio: Unity’s audio filters, mixer effects and DSP aren’t there, and a browser starts sound only once the player has pressed something (PlayerTwo’s player lets your frame play sound where the browser allows it). PlayerTwo’s Game volume reaches Unity’s sound by itself.
- **Saves:** PlayerPrefs and files under `Application.persistentDataPath` follow the player on PlayerTwo ([saves](https://playertwo.plus/docs/hosting#saves)); call `PlayerPrefs.Save()` after something worth keeping changes. Unity’s download cache stays on the device, and Unity’s Caching API isn’t in WebGL.
- **Closing:** `P2.OnFlush` is heard at once, not in `Update`; calls you make in it are waited for, a moment and a half at most.
- **Exceptions:** an exception your callback throws is caught and logged, as far as WebGL’s Enable Exceptions setting lets C# catch it: at None, any exception stops the game; Explicitly Thrown Exceptions Only catches a `throw` but not a null reference; Full catches both. `P2.Errors.CatchExceptions()` sends each one Unity logs to your studio.
- **Donations** open at once from the player’s press: call `P2.Donate.Open()` in the frame you read it.
- **Cost:** every call crosses as JSON text, a few microseconds; `room.SyncStep` makes a little garbage each frame (a string each way).
- **Compressed builds** (Brotli or gzip) are served with their encoding: no decompression fallback needed. Unity’s templates have inline scripts: fine on PlayerTwo, not [in Discord](https://playertwo.plus/docs/hosting#discord).

## Godot web

### Putting it in

- **Godot 4**, exporting for the Web (4.3 or later to export without threads).
- Unzip [playertwo-godot.zip](https://playertwo.plus/sdk/playertwo-godot.zip) into your project’s folder (or in the editor: AssetLib, Import): it is `addons/playertwo/`, three files: [plugin.cfg](https://playertwo.plus/sdk/godot/addons/playertwo/plugin.cfg), [plugin.gd](https://playertwo.plus/sdk/godot/addons/playertwo/plugin.gd), [p2.gd](https://playertwo.plus/sdk/godot/addons/playertwo/p2.gd).
- Turn it on in Project Settings, Plugins: it adds the autoload `P2`. Nothing to change in your export: PlayerTwo puts the SDK in your build’s page when it hosts it ([hosting](https://playertwo.plus/docs/hosting#engines-godot)).

### Starting

Await `P2.init()` once, early. Every other call waits for it (one made before it starts PlayerTwo with no options).

GDScript

```
extends Node

func _ready() -> void:
	var r := await P2.init()
	if not r.ok:
		print("Playing without PlayerTwo: ", r.code)   # "not-on-player-two"
		return
	print("Hello ", P2.player.name, ", level ", int(P2.player.level))   # P2.env: "p2" or "local"
	P2.loading_done()
	P2.overlay.connect(func(open): get_tree().paused = open)   # PlayerTwo's layer over the game
	P2.flush.connect(func(): P2.saves_put("slot-1", state))      # closing: waited for
```

Every call is awaited and gives a Dictionary: `{ ok, data }`, data the SDK’s own answer, or, refused, `{ ok: false, code, message, status, data }`. Numbers come back as floats: `int()` them. Off the web (the editor, a desktop export), every call gives `not-on-player-two` at once.

GDScript: the calls you'll use most

```
await P2.trophies_unlock("first-win")             # the player sees the toast
await P2.stats_add("duels-won", 1)                  # a trophy waiting on a stat is earned by itself
var best := await P2.scores_submit("time-attack", 83.4)
print("Rank ", int(best.data.rank), " of ", int(best.data.total))

var got := await P2.saves_get("slot-1")
if got.ok:
	state = JSON.parse_string(P2.save_text(got))
var put := await P2.saves_put("slot-1", state, 3)   # a Dictionary is kept as JSON; text and bytes too
if put.code == "version":
	print("Another device saved: version ", int(put.data.version))

var bought := await P2.store_buy("blaze-ball")
if bought.ok and bought.data.ok:
	equip(bought.data.product.key)                   # bought.data.receipt: signed, for your server
elif not bought.ok:
	print(bought.code)                               # "no-store", "guest", "owned", ...
```

### Every call

_The SDK from GDScript_

| What | GDScript | Answers |
| --- | --- | --- |
| [Start](https://playertwo.plus/docs/sdk#call-init) | `await P2.init()` | Who is playing: `P2.Player`, the game, test, demo, guest, params, env. Options: Timeout, Required, Local, Sdk. |
| [Who is playing](https://playertwo.plus/docs/sdk#call-me) | `await P2.me()` | `{ player, game, session, test, demo, from, params }` |
| [Identity for your servers](https://playertwo.plus/docs/sdk#call-identity) | `(await P2.identity()).data` | A JWT signed by PlayerTwo, ten minutes. |
| [An invite link](https://playertwo.plus/docs/sdk#call-identity) | `await P2.invite({"room": id})` | A link that opens your game with these params. |
| [The avatar](https://playertwo.plus/docs/sdk/travel#avatar) | `await P2.avatar()` | The critter's pixels and 3D model, name, level, what they wear. |
| [Their shop items](https://playertwo.plus/docs/sdk/travel#avatar-items) | `await P2.items_list()` | `[{ key, name, kind, tier, slot, worn, ... }]` |
| [Ask a guest to sign up](https://playertwo.plus/docs/sdk#sign-up) | `await P2.sign_up("To buy the Gold Pack")` | `{ ok, card? } or { ok: false, reason }` |
| [Trophies](https://playertwo.plus/docs/sdk#call-trophies) | `await P2.trophies_list()` | `{ trophies, xp, level }` |
| [Earn a trophy](https://playertwo.plus/docs/sdk#call-trophies) | `await P2.trophies_unlock("first-win")` | `{ trophy, new, n, xp, level, complete? }` |
| [Add-ons](https://playertwo.plus/docs/sdk#addons) | `await P2.addons_list() · await P2.addons_has("night-map")` | Each on sale; whether the player has one (data is true or false). |
| [The store](https://playertwo.plus/docs/sdk#store) | `await P2.store_list() · await P2.store_owned()` | Your products (coming: true lists those ahead too); what the player has. |
| [Who may buy](https://playertwo.plus/docs/sdk#store-access) | `await P2.store_access()` | `{ state, until, left?, via? }` |
| [Charges sold](https://playertwo.plus/docs/sdk#store-counts) | `await P2.store_sold(["s1:*"])` | `{ "s1:*": 40 }` |
| [Buy](https://playertwo.plus/docs/sdk#store) | `await P2.store_buy("blaze-ball")` | PlayerTwo’s own sheet; `{ ok, product, receipt, ... }`. |
| [Pay a charge](https://playertwo.plus/docs/sdk#store-charges) | `await P2.store_pay(charge_id)` | `{ ok, charge, amount, receipt, ... }` |
| [The shop screen](https://playertwo.plus/docs/sdk#store-shop) | `await P2.store_open("skin")` | PlayerTwo’s own shop over the game; when it closes, `{ ok, bought: [...] }`. |
| [Try-on](https://playertwo.plus/docs/sdk#store-shop) | `await P2.store_try_on() · P2.try_on.connect(...)` | The product the player looks at in the shop screen, then null. |
| [The daily deal](https://playertwo.plus/docs/sdk#store-deal) | `await P2.store_deal()` | `{ product, percent, price, was, ends } or null` |
| [Donations](https://playertwo.plus/docs/sdk#donate) | `await P2.donate_available() · await P2.donate_open()` | Whether they're on; PlayerTwo's sheet, from the player's press. |
| [The Donate button](https://playertwo.plus/docs/sdk#donate) | `await P2.donate_button("bottom-right") · await P2.donate_remove()` | `{ shown } · { removed }` |
| [Moments](https://playertwo.plus/docs/sdk#moments) | `await P2.moments_offer()` | `{ offered, shared }` |
| [Notifications](https://playertwo.plus/docs/sdk#notify) | `await P2.notify_ask("to tell you ...") · await P2.notify_allowed()` | `{ allowed, asked } · true or false` |
| [The device](https://playertwo.plus/docs/sdk#device) | `await P2.device_get()` | `{ tier, phone, touch, memory, cores, gpu, fps, ... }` |
| [Stats](https://playertwo.plus/docs/sdk#call-stats) | `await P2.stats_get() · await P2.stats_get("kills")` | Every stat, or one (a number). |
| [Change a stat](https://playertwo.plus/docs/sdk#call-stats) | `await P2.stats_set("kills", 9) · await P2.stats_add("kills")` | `{ stats, unlocked }` |
| [Leaderboards](https://playertwo.plus/docs/sdk#call-scores) | `await P2.scores_submit("time-attack", 83.4) · await P2.scores_list("time-attack", "me")` | `{ rank, total, best, ... } · { rows, total, me }` |
| [Saves](https://playertwo.plus/docs/sdk#call-saves) | `await P2.saves_list() · P2.save_text(await P2.saves_get("slot-1"))` | Slots; a save’s text (or `r.SaveBytes()`, `P2.save_bytes(result)`). |
| [Keep a save](https://playertwo.plus/docs/sdk#call-saves) | `await P2.saves_put("slot-1", state, 3) · await P2.saves_delete("slot-1")` | Text or bytes (and in GDScript a Dictionary as JSON), up to 1 MB. |
| [Presence](https://playertwo.plus/docs/sdk#call-presence) | `await P2.presence_set("Chapter 3", join)` | The line friends see; join: what they join you with. |
| [Loading and play](https://playertwo.plus/docs/sdk#call-gameplay) | `P2.loading_done() · P2.gameplay_start() · P2.gameplay_stop()` | For your studio's analytics. |
| [Your own events](https://playertwo.plus/docs/sdk#call-track) | `P2.track("level_start", {"level": 3})` | Fire and forget. |
| [Your errors](https://playertwo.plus/docs/sdk#call-crashes) | `P2.report_error(message, "Boss", str(get_stack())) · P2.errors_off()` | Fire and forget; CatchExceptions reports every exception Unity logs. |
| [Feeds](https://playertwo.plus/docs/sdk#feeds) | `await P2.feeds_get("x-posts")` | `{ at, status, body } or { at, items }` |
| [Travel](https://playertwo.plus/docs/sdk/travel#travel) | `await P2.travel_to("hoop-it") · await P2.travel_home() · await P2.travel_links()` | Doors to other games, the party with them. |
| [The party](https://playertwo.plus/docs/sdk/travel#party-play) | `await P2.party_get() · P2.party_lead() · P2.lead.connect(...)` | The party, its leader's pick now, and as it changes. |
| [The overlay and closing](https://playertwo.plus/docs/sdk#call-overlay) | `P2.overlay.connect(...) · P2.flush.connect(...)` | Pause; keep what must last (calls made then are waited for). |
| [Any call by its name](https://playertwo.plus/docs/sdk#call-init) | `await P2.call_sdk("trophies.list")` | What these files don't wrap yet. |

### Rooms

Each way into a room gives `result.room`: its `id`, `code`, `mode`, `size`, `me`, `scripted` and `open`, and its events as signals: `player_joined`, `player_left`, `player_away`, `player_back`, `host_changed`, `team_changed`, `state_changed`, `message`, `reconnecting`, `reconnected`, `moved`, `voice_changed`, `speaking_changed`, `alone`, `error`, `closed`, `sync_joined`, `sync_left`, `sync_fixed`, `object_added`, `object_removed`.

GDScript: a duel with smooth movement

```
var room

func play_online() -> void:
	var r := await P2.rooms_join({"mode": "duel", "size": 2})
	if not r.ok:
		return
	room = r.room
	room.player_joined.connect(func(p): print(p.name, " came in"))
	room.message.connect(func(kind, data, sender): if kind == "hit": take_hit(int(data.damage)))
	room.state_changed.connect(func(key, value, by): print(key, " = ", value))
	room.sync_joined.connect(func(id, values): others[id] = ghost.instantiate())
	room.closed.connect(func(why): print("Out: ", why))
	room.sync_start(["x", "y", "z", "ry"])

func _process(_delta: float) -> void:
	if room == null or not room.open:
		return
	var them: Dictionary = room.sync_step([player.position.x, player.position.y, player.position.z, player.rotation.y])
	for id in them:
		var v: Array = them[id]   # smoothed: [x, y, z, ry]
		if others.has(id):
			others[id].position = Vector3(v[0], v[1], v[2])
	if Input.is_action_just_pressed("ui_accept"):
		room.send("hit", {"damage": 12})
```

_Rooms from GDScript_

| What | GDScript |
| --- | --- |
| [Join a match, a code or your room](https://playertwo.plus/docs/sdk#rooms-join) | `(await P2.rooms_join({"mode": "duel", "size": 2})).room` |
| [A private room, the party's](https://playertwo.plus/docs/sdk#rooms-join) | `await P2.rooms_create({...}) · await P2.rooms_party({...})` |
| [A world, watching, what's live](https://playertwo.plus/docs/sdk#rooms-worlds) | `await P2.rooms_world("main", "docks") · await P2.rooms_watch(id) · await P2.rooms_live("duel")` |
| [A bad line, on purpose](https://playertwo.plus/docs/sdk#rooms-simulate) | `P2.rooms_simulate({"lag": 150, "jitter": 30, "loss": 0.02}) · P2.rooms_simulate(null)` |
| [Who, what, the host](https://playertwo.plus/docs/sdk#rooms-talk) | `room.info() · room.players() · room.state() · room.host() · room.is_host() · room.get_state("round")` |
| [Messages and shared state](https://playertwo.plus/docs/sdk#rooms-talk) | `room.send("hit", data, to) · room.set_state("round", 3)` |
| [Time and the line](https://playertwo.plus/docs/sdk#rooms-fast) | `await room.ping() · room.now() · room.stats()` |
| [Smooth movement](https://playertwo.plus/docs/sdk#rooms-sync) | `room.sync_start(fields) · room.sync_step([x, y, z, ry]) · room.sync_stop()` |
| [The room code's objects](https://playertwo.plus/docs/sdk#rooms-objects) | `room.objects_start() · room.objects_step() · room.objects_stop()` |
| [Voice chat](https://playertwo.plus/docs/sdk#rooms-voice) | `await room.voice_join() · room.voice_mute() · room.voice_volume(id, 0.5) · room.voice_leave()` |
| [Leave](https://playertwo.plus/docs/sdk#rooms-join) | `room.leave()` |

### Limits

- **GDScript only.** Godot 4’s .NET (C#) projects can’t export to the web, so the add-on is GDScript.
- **The Compatibility renderer** is the only one on the web (Forward+ and Mobile aren’t).
- **Threads** need SharedArrayBuffer: turn on Cross-origin isolation in your studio ([SharedArrayBuffer](https://playertwo.plus/docs/hosting#engines-sab)). Since Godot 4.3, a build exported without threads needs nothing, and that’s the one Safari, phones and Discord play best.
- **Safari:** Safari and iOS have had WebGL 2 bugs that break some Godot 4 games. Export without threads and play it on an iPhone before you ship.
- **Sound** starts only once the player has pressed something. PlayerTwo’s Game volume reaches it by itself.
- **Saves:** files under `user://` follow the player on PlayerTwo ([saves](https://playertwo.plus/docs/hosting#saves)).
- **Closing:** the `flush` signal; the calls you start while you hear it, before any `await`, are waited for, a moment and a half at most.
- **Plain values only** cross: numbers, text, bools, Arrays and Dictionaries. Send a Vector3 as `{"x": v.x, "y": v.y, "z": v.z}`.
- **Your errors:** GDScript’s own aren’t caught by the page; send them with `P2.report_error`.

## Testing without PlayerTwo

- **In the Unity editor, or off the web in Godot:** every call answers `not-on-player-two`, and nothing else happens: your game plays on without services.
- **In a browser on localhost** (Unity’s Build And Run, Godot’s Run in Browser): the bridge loads the SDK from PlayerTwo (`https://playertwo.plus/sdk/v1.js`, or Init’s `Sdk` option) and its stand-in answers every call from memory (env `"local"`). Give it your trophies, add-ons, products and params with Init’s `Local` (`{"trophies": [{"key": "first-win", "name": "First win", "tier": 1}]}` in C#, a Dictionary in Godot), as in [building without PlayerTwo](https://playertwo.plus/docs/sdk#start-local). Two tabs are two players in its rooms.
- **On PlayerTwo:** [push the build](https://playertwo.plus/docs/hosting#push) and play it from its page as its developer: [test mode](https://playertwo.plus/docs/sdk#test), where trophies and purchases are tests.
- **Anywhere else** (another site): the bridge asks the page around the game only if it is in a frame, a second and a half at most, and otherwise loads nothing; every call answers `not-on-player-two`. With `Required` (`required`), the page says “Play this on PlayerTwo” instead and Init never answers.

## What stays in JavaScript

A few parts of the SDK hand your game a JavaScript object to run each frame, which a bridge can’t do well; they stay JavaScript-only for now:

- **Input-run rooms** (`room.inputs`): your game’s own step runs in the page, many times a frame.
- **Replays** (`rooms.replays`, `rooms.replay` and its controls). Watching a live room works.
- **Binding your objects** (`sync.bind`, `objects.bind`): you get the values each frame instead, as above.
- **The Donate button inside an element of yours**: a corner of the page only.

Anything else by its name: `P2.Call`, `P2.call_sdk`.

## How it works

The plugin and the add-on carry the same small piece of JavaScript, run in your game’s page. It calls `window.PlayerTwo`, the SDK PlayerTwo puts first in every page of a build it hosts, and loads it from PlayerTwo only where it may answer (in a frame, or on localhost). Your engine sends it each call’s name and arguments as JSON text; it answers each call once, as JSON text, and tells your engine what PlayerTwo says (the overlay, closing, the party’s leader, a room’s events). Unity reaches it through the jslib’s four functions, Godot through `JavaScriptBridge`. Nothing is sent anywhere but through the SDK, and your game never holds the player’s sign-in.

> The files are plain text, each served on its own too: [/sdk/unity/](https://playertwo.plus/sdk/unity/P2.cs) and [/sdk/godot/addons/playertwo/](https://playertwo.plus/sdk/godot/addons/playertwo/p2.gd). On a computer, a game the PlayerTwo app installs uses [its own helpers](https://playertwo.plus/docs/sdk#launcher) instead.
