Example
Character Creation System
A host-based character creation and persistence system for PurrNet. The host stores all player saves in a server-side dictionary. When a player joins: if the host recognises their persistent ID (Steam, GUID) they load their saved character; if not, they create a new one. Progress is saved whenever a player leaves.
Host Character Database
๐น
You
Archer ยท Lv 7
PID:1003
Host found your save. Load to continue your progress.
Host Save Database3 records
โ๏ธ
Alice
Warrior ยท Lv 14
PID:1001
๐ฎ
Bob
Mage ยท Lv 9
PID:1002
๐น
You
Archer ยท Lv 7
PID:1003
How it works: new vs returning player
- Player connects โ their
OnlinePlayer.OnSpawnedfires โ callsCheckSaveServerRpc(persistentId). - Host checks its in-memory
_database. - Returning player: host calls
RpcLoadCharacter(target, savedData)โ client enters game with their character. - New player: host calls
RpcShowCreationScreen(target)โ client fills in the UI โ callsCreateCharacterServerRpcโ host stores it โ client enters game. - On disconnect: host snapshots the character from the player object and updates the record.
The database is never synced to other clients โ it lives only on the host. Each player receives only their own data via TargetRpc.
| Parameter | Type | Default | Description |
|---|---|---|---|
CheckSaveServerRpc(string playerId) | ServerRpc | โ | Client sends its persistent ID (Steam ID, device ID, etc.). Server checks the in-memory database and responds via TargetRpc with either a saved character or a flag to show the creation screen. |
CreateCharacterServerRpc(CharacterData data) | ServerRpc | โ | New player sends their chosen character. Server validates uniqueness, stores it, and sends the character back via TargetRpc to confirm. |
RpcShowCreationScreen(PlayerID) | TargetRpc | โ | Server tells only the new player to display the character creation UI. Other players are unaffected. |
RpcLoadCharacter(PlayerID, CharacterData) | TargetRpc | โ | Server sends the returning player's stored character. The client applies it locally and enters the game. |
_database (Dictionary<string, CharacterData>) | Server-only | โ | Host-side dictionary mapping persistent player ID โ CharacterData. Never synced โ no other player needs another player's creation data. |
CharacterData struct
CharacterData.cs
using System;
using PurrNet;
using UnityEngine;
public enum CharacterClass { Warrior, Mage, Archer, Rogue }
[Serializable]
[RegisterNetworkType(typeof(CharacterData))]
public struct CharacterData : IPackedAuto
{
public string name;
public CharacterClass charClass;
public int level;
public float health;
public int xp;
public int gold;
}
[Serializable]
public class SavedCharacter
{
public CharacterData data;
public DateTime createdAt;
public DateTime lastSeen;
public int sessionsPlayed;
}NetworkCharacterManager โ host database
NetworkCharacterManager.cs
using System;
using System.Collections.Generic;
using PurrNet;
using UnityEngine;
/// <summary>
/// Host-authoritative character creation and save system.
/// Attach to a DontDestroyOnLoad NetworkBehaviour on the host.
/// </summary>
public class NetworkCharacterManager : NetworkBehaviour
{
// โโ Host-only database โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// Key = persistent player identifier (Steam ID, GUID, etc.)
private readonly Dictionary<string, SavedCharacter> _database = new();
// โโ Step 1: client connects and checks for an existing save โโโโโโโโโโโโโโ
protected override void OnPlayerJoined(PlayerID id)
{
// Give the client a moment to initialize before asking
// (alternatively, let the client call CheckSaveServerRpc from their own OnSpawned)
}
/// <summary>Client calls this from OnSpawned to find out if they have a save.</summary>
[ServerRpc]
public void CheckSaveServerRpc(string persistentId)
{
if (_database.TryGetValue(persistentId, out SavedCharacter saved))
{
saved.lastSeen = DateTime.UtcNow;
saved.sessionsPlayed++;
_database[persistentId] = saved;
// Returning player โ load their character
RpcLoadCharacter(networkManager.GetCaller(), saved.data);
}
else
{
// New player โ ask them to create a character
RpcShowCreationScreen(networkManager.GetCaller());
}
}
// โโ Step 2a: new player creates a character โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
[ServerRpc]
public void CreateCharacterServerRpc(string persistentId, CharacterData data)
{
// Validate: no duplicate names (optional rule)
foreach (var save in _database.Values)
{
if (string.Equals(save.data.name, data.name, StringComparison.OrdinalIgnoreCase))
{
RpcNameTaken(networkManager.GetCaller());
return;
}
}
// Store the new character
var newSave = new SavedCharacter
{
data = data,
createdAt = DateTime.UtcNow,
lastSeen = DateTime.UtcNow,
sessionsPlayed = 1,
};
_database[persistentId] = newSave;
// Confirm and load the character on the creator's machine
RpcLoadCharacter(networkManager.GetCaller(), data);
}
// โโ Step 2b: returning player receives their saved character โโโโโโโโโโโโโโ
/// <summary>Server โ only this client: show creation UI.</summary>
[TargetRpc]
private void RpcShowCreationScreen(PlayerID target)
{
CharacterCreationUI.Show(OnCreateConfirmed);
}
/// <summary>Server โ only this client: load the saved character and enter game.</summary>
[TargetRpc]
private void RpcLoadCharacter(PlayerID target, CharacterData data)
{
CharacterCreationUI.Hide();
LocalCharacterStore.Apply(data); // writes to local PlayerPrefs as cache
GameSceneLoader.LoadGameScene();
}
[TargetRpc]
private void RpcNameTaken(PlayerID target)
=> CharacterCreationUI.ShowError("That name is already taken โ choose another.");
// โโ Persistence โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
protected override void OnPlayerLeft(PlayerID id)
{
// Snapshot the leaving player's current character state
if (OnlinePlayer.TryGetPlayer(id, out OnlinePlayer p))
{
string key = p.persistentId; // stored when player first joined
if (_database.TryGetValue(key, out SavedCharacter save))
{
save.data = p.GetCharacterSnapshot();
save.lastSeen = DateTime.UtcNow;
_database[key] = save;
}
}
}
/// <summary>
/// Serialize the database to disk so it survives host restarts.
/// Call from OnApplicationQuit and after any significant change.
/// </summary>
[Server]
public void SaveDatabaseToDisk()
{
var wrapper = new DatabaseWrapper { records = new List<DatabaseEntry>() };
foreach (var kv in _database)
wrapper.records.Add(new DatabaseEntry { id = kv.Key, save = kv.Value });
string json = JsonUtility.ToJson(wrapper, prettyPrint: true);
System.IO.File.WriteAllText(Application.persistentDataPath + "/characters.json", json);
Debug.Log($"[CharacterDB] Saved {_database.Count} records.");
}
[Server]
public void LoadDatabaseFromDisk()
{
string path = Application.persistentDataPath + "/characters.json";
if (!System.IO.File.Exists(path)) return;
var wrapper = JsonUtility.FromJson<DatabaseWrapper>(System.IO.File.ReadAllText(path));
_database.Clear();
foreach (var entry in wrapper.records) _database[entry.id] = entry.save;
Debug.Log($"[CharacterDB] Loaded {_database.Count} records.");
}
// โโ Callback from creation UI (owner client) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
private void OnCreateConfirmed(CharacterData data)
{
string persistentId = GetPersistentId(); // Steam ID, GUID, etc.
CreateCharacterServerRpc(persistentId, data);
}
private static string GetPersistentId()
{
// Use Steam ID if available, otherwise fall back to a device GUID
if (SteamInitializer.IsInitialized)
return SteamInitializer.LocalSteamId.ToString();
if (!PlayerPrefs.HasKey("DeviceId"))
PlayerPrefs.SetString("DeviceId", Guid.NewGuid().ToString());
return PlayerPrefs.GetString("DeviceId");
}
// โโ Inner types for JSON serialization โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
[Serializable] private class DatabaseWrapper { public List<DatabaseEntry> records; }
[Serializable] private class DatabaseEntry { public string id; public SavedCharacter save; }
}OnlinePlayer โ client boot
OnlinePlayer.cs
using PurrNet;
using UnityEngine;
/// <summary>
/// On the local client's player object โ calls CheckSaveServerRpc
/// immediately after spawning so the host can determine new vs. returning.
/// </summary>
public class OnlinePlayer : PlayerIdentity<OnlinePlayer>
{
public string persistentId { get; private set; }
protected override void OnSpawned()
{
if (!isLocalPlayer) return;
persistentId = NetworkCharacterManager.GetPersistentId(); // same helper as manager
// Ask the host whether we have a save
var manager = FindObjectOfType<NetworkCharacterManager>();
if (manager != null) manager.CheckSaveServerRpc(persistentId);
}
public CharacterData GetCharacterSnapshot() => LocalCharacterStore.Current;
}Use a persistent ID, not PlayerID
PlayerID changes each session. Use Steam ID, a GUID stored in PlayerPrefs, or an account token as the dictionary key so you can match the same physical player across sessions even if they reconnect with a different PlayerID.Validate character data on the server
A client could send a crafted
CharacterData with max stats. Validate max values, name length, and allowed class IDs inside CreateCharacterServerRpc before storing. Never trust client-supplied data at face value.SaveDatabaseToDisk for persistent worlds
In-memory saves are lost when the host exits. Call
SaveDatabaseToDisk() in OnApplicationQuit and LoadDatabaseFromDisk() in Awake to persist characters across host restarts.