Unity WebGL
Putting it in
- Unity 2021.3 or later, Unity 6 included, building for WebGL.
- Unzip playertwo-unity.zip into your project’s folder:
Assets/Plugins/WebGL/PlayerTwo.jslib(the browser half) andAssets/PlayerTwo/P2.csandP2Runner.cs(the C# half). Or take the files one by one: PlayerTwo.jslib, P2.cs, 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). 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).
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.
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 TaskEvery call
| What | C# | Answers |
|---|---|---|
| Start | P2.Init(r => ...) | Who is playing: P2.Player, the game, test, demo, guest, params, env. Options: Timeout, Required, Local, Sdk. |
| Who is playing | P2.Me(r => ...) | { player, game, session, test, demo, from, params } |
| Identity for your servers | P2.Identity(r => Send(r.Data.Str)) | A JWT signed by PlayerTwo, ten minutes. |
| An invite link | P2.Invite(new Dictionary<string, string> { { "room", id } }, r => ...) | A link that opens your game with these params. |
| The avatar | P2.Avatar(r => ...) | The critter's pixels and 3D model, name, level, what they wear. |
| Their shop items | P2.Items.List(r => ...) | [{ key, name, kind, tier, slot, worn, ... }] |
| Ask a guest to sign up | P2.SignUp("To buy the Gold Pack") | { ok, card? } or { ok: false, reason } |
| Trophies | P2.Trophies.List(r => ...) | { trophies, xp, level } |
| Earn a trophy | P2.Trophies.Unlock("first-win") | { trophy, new, n, xp, level, complete? } |
| Add-ons | 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 | P2.Store.List(r => ...) · P2.Store.Owned(r => ...) | Your products (coming: true lists those ahead too); what the player has. |
| Who may buy | P2.Store.Access(r => ...) | { state, until, left?, via? } |
| Charges sold | P2.Store.Sold(new[] { "s1:*" }, r => ...) | { "s1:*": 40 } |
| Buy | P2.Store.Buy("blaze-ball", r => ...) | PlayerTwo’s own sheet; { ok, product, receipt, ... }. |
| Pay a charge | P2.Store.Pay(chargeId, r => ...) | { ok, charge, amount, receipt, ... } |
| The shop screen | P2.Store.Open(r => ..., kind: "skin") | PlayerTwo’s own shop over the game; when it closes, { ok, bought: [...] }. |
| Try-on | P2.Store.TryOn() · P2.OnTryOn += item => ... | The product the player looks at in the shop screen, then null. |
| The daily deal | P2.Store.Deal(r => ...) | { product, percent, price, was, ends } or null |
| Donations | P2.Donate.Available(r => ...) · P2.Donate.Open() | Whether they're on; PlayerTwo's sheet, from the player's press. |
| The Donate button | P2.Donate.Button("bottom-right") · P2.Donate.RemoveButton() | { shown } · { removed } |
| Moments | P2.Moments.Offer() | { offered, shared } |
| Notifications | P2.Notify.Ask("to tell you when your crops are ready", r => ...) · P2.Notify.Allowed(r => ...) | { allowed, asked } · true or false |
| The device | P2.Device.Get(r => ...) | { tier, phone, touch, memory, cores, gpu, fps, ... } |
| Stats | P2.Stats.All(r => ...) · P2.Stats.Get("kills", r => ...) | Every stat, or one (a number). |
| Change a stat | P2.Stats.Set("kills", 9) · P2.Stats.Add("kills", 1) | { stats, unlocked } |
| Leaderboards | P2.Scores.Submit("time-attack", 83.4) · P2.Scores.List("time-attack", r => ..., "me") | { rank, total, best, ... } · { rows, total, me } |
| 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 | 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 | P2.Presence.Set("Chapter 3", join) | The line friends see; join: what they join you with. |
| Loading and play | P2.Loading.Done() · P2.Gameplay.Start() · P2.Gameplay.Stop() | For your studio's analytics. |
| Your own events | P2.Track("level_start", new Dictionary<string, object> { { "level", 3 } }) | Fire and forget. |
| Your errors | P2.Errors.Report(message, "Boss", stack) · P2.Errors.CatchExceptions() · P2.Errors.Off() | Fire and forget; CatchExceptions reports every exception Unity logs. |
| Feeds | P2.Feeds.Get("x-posts", r => ...) | { at, status, body } or { at, items } |
| Travel | P2.Travel.To("hoop-it") · P2.Travel.Home() · P2.Travel.Links(r => ...) | Doors to other games, the party with them. |
| The party | 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 | P2.OnOverlay += open => ... · P2.OnFlush += () => ... | Pause; keep what must last (calls made then are waited for). |
| Any call by its name | 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.
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 } });
}| What | C# |
|---|---|
| Join a match, a code or your room | P2.Rooms.Join(new P2RoomOptions { Mode = "duel", Size = 2 }, r => room = r.Room) |
| A private room, the party's | P2.Rooms.Create(options, cb) · P2.Rooms.Party(options, cb) |
| A world, watching, what's live | P2.Rooms.World("main", cb, "docks") · P2.Rooms.Watch(id, cb) · P2.Rooms.Live("duel", cb) |
| A bad line, on purpose | P2.Rooms.Simulate(150, 30, 0.02) · P2.Rooms.StopSimulating() |
| Who, what, the host | room.Info() · room.Players · room.State · room.Host · room.IsHost · room.Get("round") |
| Messages and shared state | room.Send("hit", data) · room.SendTo("hit", data, ids) · room.Set("round", 3) |
| Time and the line | room.Ping(r => ...) · room.Now() · room.Stats() |
| Smooth movement | room.SyncStart(fields) · room.SyncStep(x, y, z, ry) · room.SyncStop() |
| The room code's objects | room.ObjectsStart() · room.ObjectsStep() · room.ObjectsStop() |
| Voice chat | room.VoiceJoin() · room.VoiceMute() · room.VoiceVolume(id, 0.5) · room.VoiceLeave() |
| Leave | 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;
awaitonP2.Asyncgoes on there too.Task.RunandSystem.Threadingdon’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.persistentDataPathfollow the player on PlayerTwo (saves); callPlayerPrefs.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.OnFlushis heard at once, not inUpdate; 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
throwbut 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.SyncStepmakes 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.
Godot web
Putting it in
- Godot 4, exporting for the Web (4.3 or later to export without threads).
- Unzip playertwo-godot.zip into your project’s folder (or in the editor: AssetLib, Import): it is
addons/playertwo/, three files: plugin.cfg, plugin.gd, 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).
Starting
Await P2.init() once, early. Every other call waits for it (one made before it starts PlayerTwo with no options).
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 forEvery 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.
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
| What | GDScript | Answers |
|---|---|---|
| Start | await P2.init() | Who is playing: P2.Player, the game, test, demo, guest, params, env. Options: Timeout, Required, Local, Sdk. |
| Who is playing | await P2.me() | { player, game, session, test, demo, from, params } |
| Identity for your servers | (await P2.identity()).data | A JWT signed by PlayerTwo, ten minutes. |
| An invite link | await P2.invite({"room": id}) | A link that opens your game with these params. |
| The avatar | await P2.avatar() | The critter's pixels and 3D model, name, level, what they wear. |
| Their shop items | await P2.items_list() | [{ key, name, kind, tier, slot, worn, ... }] |
| Ask a guest to sign up | await P2.sign_up("To buy the Gold Pack") | { ok, card? } or { ok: false, reason } |
| Trophies | await P2.trophies_list() | { trophies, xp, level } |
| Earn a trophy | await P2.trophies_unlock("first-win") | { trophy, new, n, xp, level, complete? } |
| Add-ons | 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 | await P2.store_list() · await P2.store_owned() | Your products (coming: true lists those ahead too); what the player has. |
| Who may buy | await P2.store_access() | { state, until, left?, via? } |
| Charges sold | await P2.store_sold(["s1:*"]) | { "s1:*": 40 } |
| Buy | await P2.store_buy("blaze-ball") | PlayerTwo’s own sheet; { ok, product, receipt, ... }. |
| Pay a charge | await P2.store_pay(charge_id) | { ok, charge, amount, receipt, ... } |
| The shop screen | await P2.store_open("skin") | PlayerTwo’s own shop over the game; when it closes, { ok, bought: [...] }. |
| Try-on | await P2.store_try_on() · P2.try_on.connect(...) | The product the player looks at in the shop screen, then null. |
| The daily deal | await P2.store_deal() | { product, percent, price, was, ends } or null |
| Donations | await P2.donate_available() · await P2.donate_open() | Whether they're on; PlayerTwo's sheet, from the player's press. |
| The Donate button | await P2.donate_button("bottom-right") · await P2.donate_remove() | { shown } · { removed } |
| Moments | await P2.moments_offer() | { offered, shared } |
| Notifications | await P2.notify_ask("to tell you ...") · await P2.notify_allowed() | { allowed, asked } · true or false |
| The device | await P2.device_get() | { tier, phone, touch, memory, cores, gpu, fps, ... } |
| Stats | await P2.stats_get() · await P2.stats_get("kills") | Every stat, or one (a number). |
| Change a stat | await P2.stats_set("kills", 9) · await P2.stats_add("kills") | { stats, unlocked } |
| Leaderboards | await P2.scores_submit("time-attack", 83.4) · await P2.scores_list("time-attack", "me") | { rank, total, best, ... } · { rows, total, me } |
| 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 | 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 | await P2.presence_set("Chapter 3", join) | The line friends see; join: what they join you with. |
| Loading and play | P2.loading_done() · P2.gameplay_start() · P2.gameplay_stop() | For your studio's analytics. |
| Your own events | P2.track("level_start", {"level": 3}) | Fire and forget. |
| Your errors | P2.report_error(message, "Boss", str(get_stack())) · P2.errors_off() | Fire and forget; CatchExceptions reports every exception Unity logs. |
| Feeds | await P2.feeds_get("x-posts") | { at, status, body } or { at, items } |
| 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 | 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 | P2.overlay.connect(...) · P2.flush.connect(...) | Pause; keep what must last (calls made then are waited for). |
| Any call by its name | 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.
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})| What | GDScript |
|---|---|
| Join a match, a code or your room | (await P2.rooms_join({"mode": "duel", "size": 2})).room |
| A private room, the party's | await P2.rooms_create({...}) · await P2.rooms_party({...}) |
| A world, watching, what's live | await P2.rooms_world("main", "docks") · await P2.rooms_watch(id) · await P2.rooms_live("duel") |
| A bad line, on purpose | P2.rooms_simulate({"lag": 150, "jitter": 30, "loss": 0.02}) · P2.rooms_simulate(null) |
| Who, what, the host | room.info() · room.players() · room.state() · room.host() · room.is_host() · room.get_state("round") |
| Messages and shared state | room.send("hit", data, to) · room.set_state("round", 3) |
| Time and the line | await room.ping() · room.now() · room.stats() |
| Smooth movement | room.sync_start(fields) · room.sync_step([x, y, z, ry]) · room.sync_stop() |
| The room code's objects | room.objects_start() · room.objects_step() · room.objects_stop() |
| Voice chat | await room.voice_join() · room.voice_mute() · room.voice_volume(id, 0.5) · room.voice_leave() |
| Leave | 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). 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). - Closing: the
flushsignal; the calls you start while you hear it, before anyawait, 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’sSdkoption) and its stand-in answers every call from memory (env"local"). Give it your trophies, add-ons, products and params with Init’sLocal({"trophies": [{"key": "first-win", "name": "First win", "tier": 1}]}in C#, a Dictionary in Godot), as in building without PlayerTwo. Two tabs are two players in its rooms. - On PlayerTwo: push the build and play it from its page as its developer: test mode, 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. WithRequired(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.replayand 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.