Local Character to Online
Take a character that lives on the player's local machine and bring it into a live PurrNet multiplayer session — preserving stats, joining a friend's lobby, letting the host read everyone's data, and saving progress back when a player leaves.
Character data lives locally before any network connection. Save stats, level, and progress to PlayerPrefs or a JSON file so the player owns their character across sessions.
[Serializable]
public class CharacterData
{
public string name = "Hero";
public int level = 1;
public float health = 100f;
public int xp = 0;
}
public static class CharacterSave
{
const string KEY = "CharacterData";
public static void Save(CharacterData data)
{
PlayerPrefs.SetString(KEY, JsonUtility.ToJson(data));
PlayerPrefs.Save();
}
public static CharacterData Load()
{
string json = PlayerPrefs.GetString(KEY, "{}");
return JsonUtility.FromJson<CharacterData>(json)
?? new CharacterData();
}
}Key API at each stage
| Parameter | Type | Default | Description |
|---|---|---|---|
CharacterSave.Save(data) | void | — | Serializes CharacterData to JSON and writes it to PlayerPrefs. Call before any scene transition or disconnect. |
CharacterSave.Load() | CharacterData | — | Reads the saved JSON from PlayerPrefs. Returns a default CharacterData if no save exists yet. |
NetworkManager.StartHost() | void | — | Starts PurrNet as both server and client on this machine. Spawns the local player prefab automatically. |
NetworkManager.StartClient(address) | void | — | Connects to an existing session. Once connected, the server spawns a PlayerIdentity object for this client. |
OnSpawned() | override void | — | Called by PurrNet after the player object is spawned and registered. The safe place to push saved character data into SyncVars. |
OnPlayerLeft(PlayerID) | override void | — | Server-only callback. Fires before the player object is despawned. Use it to capture and persist the player's final state. |
Step 1 — Save the character locally
The character exists before any network connection. Serialize your data class to PlayerPrefs or a file so it persists across game sessions and is always available when starting offline or transitioning to online.
using System;
using UnityEngine;
[Serializable]
public class CharacterData
{
public string name = "Hero";
public int level = 1;
public float health = 100f;
public int xp = 0;
// Add any stat you want to persist across sessions
}
public static class CharacterSave
{
private const string KEY = "CharacterData";
/// <summary>Persist character to local storage.</summary>
public static void Save(CharacterData data)
{
PlayerPrefs.SetString(KEY, JsonUtility.ToJson(data));
PlayerPrefs.Save();
}
/// <summary>Load character from local storage. Never returns null.</summary>
public static CharacterData Load()
{
string json = PlayerPrefs.GetString(KEY, "{}");
return JsonUtility.FromJson<CharacterData>(json) ?? new CharacterData();
}
}Step 2 — Connect and sync character data
Subclass PlayerIdentity<T> for your player prefab. In OnSpawned, load the local save and write it into SyncVars. PurrNet replicates the values to all peers automatically — no extra RPC needed.
using PurrNet;
using UnityEngine;
/// <summary>Bridges local save data into the PurrNet network session.</summary>
public class OnlinePlayer : PlayerIdentity<OnlinePlayer>
{
// ownerAuth: true lets the owning client write without a ServerRpc
private SyncVar<string> _name = new("Hero", ownerAuth: true);
private SyncVar<int> _level = new(1, ownerAuth: true);
private SyncVar<float> _health = new(100f, ownerAuth: true);
private SyncVar<int> _xp = new(0, ownerAuth: true);
public string charName => _name.value;
public int level => _level.value;
public float health => _health.value;
protected override void OnSpawned()
{
if (!isLocalPlayer) return;
// Push the local save into the network — all peers see this
CharacterData saved = CharacterSave.Load();
_name.value = saved.name;
_level.value = saved.level;
_health.value = saved.health;
_xp.value = saved.xp;
Debug.Log($"[Net] Spawned as {saved.name} lv{saved.level}");
}
}ownerAuth: true for character stats
ownerAuth: true on a SyncVar lets the owning client write directly without going through a ServerRpc. This is safe for cosmetic and progression data that the server will validate on use — but avoid it for anything the server must enforce (HP in a combat game, currency, etc.).Step 3 — Host reads and uses player data
Once all players are spawned, the host can iterate OnlinePlayer.allPlayers to read every character and apply server-side logic — level-scaling, matchmaking balance, anti-cheat checks, and targeted RPCs.
using PurrNet;
using UnityEngine;
public class MatchManager : NetworkBehaviour
{
/// <summary>Called by host when all players are ready.</summary>
[Server]
public void StartMatch()
{
foreach (OnlinePlayer p in OnlinePlayer.allPlayers)
{
// Balance: give level-scaled health at match start
float maxHp = 100f + (p.level * 10f);
RpcSetMaxHealth(p.playerID, maxHp);
Debug.Log($" {p.charName} lv{p.level} → {maxHp} max HP");
}
}
/// <summary>Runs only on the targeted client.</summary>
[TargetRpc]
private void RpcSetMaxHealth(PlayerID target, float maxHp)
{
GetComponent<HealthSystem>().SetMax(maxHp);
}
// Look up any specific player by connection ID
[Server]
public void AwardXP(PlayerID id, int amount)
{
if (!OnlinePlayer.TryGetPlayer(id, out OnlinePlayer p)) return;
p._xp.value += amount;
}
}Step 4 — Save data when a player leaves
Override OnPlayerLeft on a server-side NetworkBehaviour. This fires before the player object is despawned, giving you a guaranteed window to capture and persist their final state.
using PurrNet;
using UnityEngine;
public class SessionManager : NetworkBehaviour
{
/// <summary>Server: fires before the player object is despawned.</summary>
protected override void OnPlayerLeft(PlayerID id)
{
if (!OnlinePlayer.TryGetPlayer(id, out OnlinePlayer p)) return;
var snapshot = new CharacterData
{
name = p.charName,
level = p.level,
health = p.health,
xp = p._xp.value,
};
// Tell the leaving client to write the snapshot locally
RpcSaveOnClient(id, snapshot);
// Optionally persist to your own backend
StartCoroutine(SaveToBackend(id.ToString(), snapshot));
}
[TargetRpc]
private void RpcSaveOnClient(PlayerID target, CharacterData data)
{
CharacterSave.Save(data);
Debug.Log("[Save] Progress kept for next session.");
}
}Always save on unexpected disconnect
OnApplicationQuit and subscribe to NetworkManager.onClientDisconnectedon the client side too. A player losing internet or force-quitting won't trigger OnPlayerLeft cleanly — save locally from the client as a fallback before the RPC can arrive.This pattern works with any PurrNet transport