Example
Grid Survival Crafting
A host-world grid crafting system for PurrNet. The shared world grid is stored as a SyncDictionary so all peers instantly see placements. Multi-cell furniture (sofa, workbench) occupies multiple grid cells validated server-side. Each player has individual progress โ returning players resume where they left off; new players start fresh.
Grid World โ Host Synced
0 placed
Click to place ยท Click occupied cell to remove
Host World
Grid: 8ร5
Items: 0
SyncDictionary<Vector2Int,int>
Player
Loads saved progress from host
Architecture: shared world, individual progress
The grid world has two layers of data:
- Shared world โ the
SyncDictionary<Vector2Int, int>that all peers see. Every placement or removal is authoritative server-side and instantly replicated. - Individual progress โ each player's inventory, health, and position. Stored server-side in a plain
Dictionary<string, PlayerWorldData>(not synced โ no one needs to see another player's save). Restored viaTargetRpcwhen that player joins.
| Parameter | Type | Default | Description |
|---|---|---|---|
SyncDictionary<Vector2Int, int> | SyncDictionary | โ | The world grid. Key = grid position, value = item ID. Automatically replicated to all peers on change. Late-joining clients receive the full current state on connect. |
PlaceItemServerRpc(Vector2Int[] cells, int itemId) | ServerRpc | โ | Client sends the cells it wants to fill and the item ID. Server validates all cells are empty and within bounds before writing to the SyncDictionary. |
RemoveItemServerRpc(Vector2Int anchor) | ServerRpc | โ | Client sends the anchor cell. Server finds all cells the item occupies (via item size), removes them all atomically. |
OnPlayerJoined(PlayerID) | override | โ | Server checks the player's ID against _playerSaves. Returning players load their inventory and progress; new players receive an empty inventory and start fresh. |
OnPlayerLeft(PlayerID) | override | โ | Server saves the leaving player's inventory and progress to the in-memory dictionary before their object is despawned. |
World grid + per-player saves
NetworkWorldGrid.cs
using System;
using System.Collections.Generic;
using PurrNet;
using UnityEngine;
[Serializable]
public class PlayerWorldData
{
public List<InventoryItem> inventory = new();
public Vector3 spawnPosition;
public float health = 100f;
}
[Serializable]
public class InventoryItem { public int itemId; public int count; }
/// <summary>
/// Host-authoritative world grid. Shared across all players.
/// Each player has individual progress saved per PlayerID.
/// </summary>
public class NetworkWorldGrid : NetworkBehaviour
{
[Header("Grid Size")]
[SerializeField] private int _cols = 16;
[SerializeField] private int _rows = 16;
[Header("Item Database")]
[SerializeField] private ItemDatabase _itemDb;
// โโ Shared world state (all peers mirror this) โโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// <summary>Key = grid cell position, Value = item prefab ID.</summary>
private SyncDictionary<Vector2Int, int> _worldGrid = new();
// โโ Per-player saves (host memory only) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
private readonly Dictionary<string, PlayerWorldData> _playerSaves = new();
// โโ Lifecycle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
protected override void OnSpawned()
{
_worldGrid.onAdded += (pos, id) => WorldRenderer.PlaceItem(pos, id);
_worldGrid.onRemoved += (pos, _) => WorldRenderer.RemoveItem(pos);
}
protected override void OnPlayerJoined(PlayerID id)
{
string key = id.ToString();
if (_playerSaves.TryGetValue(key, out PlayerWorldData save))
{
// Returning player โ restore their progress
RpcLoadPlayerProgress(id, save);
}
else
{
// New player โ create fresh save
_playerSaves[key] = new PlayerWorldData
{
spawnPosition = FindSpawnPoint(),
};
RpcNotifyNewPlayer(id);
}
}
protected override void OnPlayerLeft(PlayerID id)
{
// Snapshot must happen before the player object is despawned
SavePlayerProgress(id);
}
// โโ Server-side placement โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
/// <summary>
/// Validate and place a multi-cell item.
/// cells[0] is the anchor โ must be same order as the client's preview.
/// </summary>
[ServerRpc]
public void PlaceItemServerRpc(Vector2Int[] cells, int itemId)
{
if (!_itemDb.TryGet(itemId, out ItemData item)) return;
if (cells.Length != item.width * item.height) return;
foreach (var cell in cells)
{
if (cell.x < 0 || cell.x >= _cols || cell.y < 0 || cell.y >= _rows) return;
if (_worldGrid.ContainsKey(cell)) return;
}
foreach (var cell in cells) _worldGrid[cell] = itemId;
}
/// <summary>Remove a multi-cell item by its anchor cell.</summary>
[ServerRpc]
public void RemoveItemServerRpc(Vector2Int anchor)
{
if (!_worldGrid.TryGetValue(anchor, out int itemId)) return;
if (!_itemDb.TryGet(itemId, out ItemData item)) return;
for (int dx = 0; dx < item.width; dx++)
for (int dy = 0; dy < item.height; dy++)
_worldGrid.Remove(new Vector2Int(anchor.x + dx, anchor.y + dy));
}
// โโ Progress save / load โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
[Server]
private void SavePlayerProgress(PlayerID id)
{
if (!OnlinePlayer.TryGetPlayer(id, out OnlinePlayer p)) return;
_playerSaves[id.ToString()] = new PlayerWorldData
{
inventory = p.GetInventorySnapshot(),
spawnPosition = p.transform.position,
health = p.health,
};
}
[TargetRpc]
private void RpcLoadPlayerProgress(PlayerID target, PlayerWorldData data)
{
PlayerProgressLoader.Apply(data);
UIManager.ShowMessage("Welcome back! Your progress has been restored.");
}
[TargetRpc]
private void RpcNotifyNewPlayer(PlayerID target)
{
UIManager.ShowMessage("New world โ start gathering resources!");
}
private Vector3 FindSpawnPoint() => Vector3.zero; // replace with your spawn logic
}Client-side placement preview
FurniturePlacer.cs
using PurrNet;
using UnityEngine;
/// <summary>
/// Client-side placement preview + commit.
/// Reads from ItemDatabase to know multi-cell footprint before sending to server.
/// </summary>
public class FurniturePlacer : NetworkBehaviour
{
[SerializeField] private NetworkWorldGrid _grid;
[SerializeField] private ItemDatabase _itemDb;
[SerializeField] private GameObject _previewPrefab;
private int _selectedItemId = -1;
private GameObject _preview;
public void SelectItem(int itemId)
{
_selectedItemId = itemId;
if (_preview != null) Destroy(_preview);
if (_itemDb.TryGet(itemId, out ItemData item))
_preview = Instantiate(_previewPrefab);
}
private void Update()
{
if (!isOwner || _selectedItemId < 0 || _preview == null) return;
// Raycast to find hovered grid cell
if (!TryGetHoveredCell(out Vector2Int anchor)) return;
// Move preview to anchor
_preview.transform.position = GridToWorld(anchor);
// Show valid / invalid tint
bool valid = CanPlace(anchor);
_preview.GetComponent<Renderer>().material.color = valid ? Color.green : Color.red;
if (Input.GetMouseButtonDown(0) && valid)
CommitPlacement(anchor);
}
private void CommitPlacement(Vector2Int anchor)
{
if (!_itemDb.TryGet(_selectedItemId, out ItemData item)) return;
// Build cell list matching the item footprint
var cells = new Vector2Int[item.width * item.height];
int idx = 0;
for (int dy = 0; dy < item.height; dy++)
for (int dx = 0; dx < item.width; dx++)
cells[idx++] = new Vector2Int(anchor.x + dx, anchor.y + dy);
_grid.PlaceItemServerRpc(cells, _selectedItemId);
}
private bool CanPlace(Vector2Int anchor)
{
// Preview validity โ server will re-validate
if (!_itemDb.TryGet(_selectedItemId, out ItemData item)) return false;
for (int dx = 0; dx < item.width; dx++)
for (int dy = 0; dy < item.height; dy++)
{
var cell = new Vector2Int(anchor.x + dx, anchor.y + dy);
if (_grid.IsCellOccupied(cell)) return false;
}
return true;
}
private bool TryGetHoveredCell(out Vector2Int cell) { cell = default; return false; } // implement with Physics.Raycast
private Vector3 GridToWorld(Vector2Int cell) => new Vector3(cell.x, 0, cell.y);
}SyncDictionary handles late joiners automatically
A player who joins mid-session receives the full current
_worldGrid snapshot on connect โ every placed item appears instantly without any extra logic. The onAdded callback fires for each entry so the renderer reacts the same way it would for a real-time placement.Always validate placement server-side
The client sends the cells it wants to fill, but the server re-validates every cell before writing. This prevents a modified client from placing items on occupied cells, outside the world boundary, or without paying the item cost.
Persisting across server restarts
_playerSaves and the world grid live in memory โ they are lost if the host closes the game. For persistent worlds, serialize _playerSaves and the grid to disk (JSON, SQLite, etc.) in OnApplicationQuit and reload on Awake.