Co-op
This guide is for programmers. It explains how Shipready saves a co-op game: who may save, how each player's own data is kept, how saved objects come back as networked objects, and what your network library still has to do. It ends with a walkthrough of the Netcode for GameObjects (NGO) sample.
Shipready has no networking code of its own. Its core works with any networking library through three small interfaces in the namespace RareGeometry.Shipready.Save.Coop. The 1.0 sample uses NGO 2.x in Unity 6, and NGO is the only library shown and tested.
Settings in bold, such as World Load Mode, are fields on the settings asset ShipreadySaveSettings. Select it in the Project window to change them.
The rules in short #
- The host owns the world. Only the host, or a solo player, saves and loads world data. A client that tries gets
HostOnly(SK140), and no file is touched. - The host loads before friends join. There is no loading during a session in 1.0.
- The host can save at any time. Clients never see the save buttons.
- Each player's own data lives in the host's save, under a stable player ID that your game supplies, such as a Steam ID.
- Shipready restores state on the host only. Your network library shows that state to the clients. Every value a client must see has to be network-synced by your game.
- Every player keeps their own settings. The global file, which holds the Settings category, stays available to clients.
The host-only model #
Who may save: ISaveAuthority #
public interface ISaveAuthority
{
bool HasSaveAuthority { get; }
}
Set it with SaveKit.Authority. Left at null, the default, the game counts as a solo game and saving is always allowed. A game with no co-op never sets it.
When HasSaveAuthority returns false, Shipready refuses these calls with HostOnly before it touches storage:
SaveKit.Save,SaveAsync,Autosave,AutosaveAsyncandQuicksaveSaveKit.Load,LoadAsync,LoadNewestAutosaveandLoadQuicksave, including the versions that take aSlotInfoSaveKit.Delete,RestoreBackupandRestoreBackupAsync
The global file stays available, so a client can still call SaveKit.SaveGlobal(), SaveGlobalAsync(), LoadGlobal() and LoadGlobalAsync(). Reading slot information, such as SaveKit.HasSave and SaveKit.GetSlotInfos, also still works. It only reads that computer's own files.
Shipready's own autosaves follow the same rule. On a client, the timer and scene-change autosaves are skipped. When Autosave On Quit is on, a client's quit saves its global file instead of an autosave. If HasSaveAuthority throws an exception, Shipready treats the answer as no and says why in the Console.
The NGO sample's authority, NgoSaveAuthority, shows the usual rule:
public bool HasSaveAuthority
{
get
{
NetworkManager manager = _manager;
if (manager == null) return true;
if (!manager.IsListening) return true;
return manager.IsServer;
}
}
- Not in a session (main menu, solo play): yes. This is what lets the host load a save before hosting.
- The host, or a dedicated server: yes, because
IsServeris true. - A connected client: no.
Set it once Shipready has started, because SaveKit.Shutdown() sets Authority, Identity and SpawnHandler back to null. With Initialise Automatically on, the default, Shipready has already started when your first scene's Awake runs; with it off, set the hooks after your own SaveKit.Initialise() call:
SaveKit.Authority = new NgoSaveAuthority(NetworkManager.Singleton);
Hiding the save buttons #
SaveKit.CanSave and SaveKit.CanLoad are true when Shipready has started and there is no authority, or the authority says yes. Both are false on a connected client.
Shipready's save menu checks them for you. A client sees the slot cards without their Save, Load, Delete and Restore backup buttons, and a line saying "Only the host can save or load." Change that line in the menu's text asset (HostOnlyLine).
For buttons of your own, check the same two properties. The sample's menu goes one step further. It shows Save only while hosting, and Load only before a session starts:
// Hide what this player may not do. A connected client gets false from both.
bool canSave = server && SaveKit.CanSave;
bool canLoad = !listening && SaveKit.CanLoad;
Clients keep their own settings #
Every copy of the game keeps its own global file, client or host. Shipready loads it when it starts, and a load of the host's world never touches it. The sample remembers the name each player types this way:
SaveKit.Data.Set(PlayerNameKey, playerName, SettingsCategory);
SaveKit.SaveGlobalAsync();
The host loads before friends join #
A co-op session runs like this:
- The host picks a save, or a new game, from the main menu.
- The game loads the world on the host before the session starts.
- The host starts the session and friends join. The network library shows them the world, and the game gives each player their own data back by player ID.
- The host can save at any time. Clients do not see the save buttons.
- When a friend leaves, their data stays in the host's save and comes back the next time they join.
Loading a different save during a session is not part of 1.0. To switch saves, end the session, load, and host again.
Saving during a session #
The host can save whenever it likes, by hand or through the autosave timer. The one exception is while SaveKit.LoadAsync is still loading the scenes of its save (see SK154), and that does not happen mid-session because the host loads first.
SaveEvents.Saving is raised before a save gathers anything, for autosaves too. Handle it to write every connected player's latest values into SaveKit.Players, so they are part of that save. The sample's bridge does exactly that.
Player IDs and per-player data #
Stable player IDs: IPlayerIdentity #
public interface IPlayerIdentity
{
bool TryGetPlayerId(ulong connectionId, out string playerId);
}
connectionIdis the network library's number for a connection. It changes every time a player connects, so it can never be the player ID. If your library usesintnumbers, convert them toulong.playerIdmust stay the same for one player across sessions. A Steam ID is a good choice, as is a platform account ID or an ID from your own login.- Return false while a player's ID is not known yet, for example before their Steam ID arrives. Do not throw. If
TryGetPlayerIdthrows, Shipready catches the exception, logs SK141 and treats the player as unknown. SaveKit.Players.ForConnection(connectionId)also logs SK141, once per connection, when no identity is set or the identity does not name the connection. That player then starts from defaults.SaveKit.Players.TryGetPlayerIdis the quiet form, for code that asks again later: it logs only when the identity throws.
Set it with SaveKit.Identity. The host usually learns a player's ID while approving the connection, so the identity is a simple map that your approval code fills in. A minimal version looks like this. The sample's NgoPlayerIdentity is the full version for NGO.
using System.Collections.Generic;
using RareGeometry.Shipready.Save.Coop;
public sealed class PlayerIdMap : IPlayerIdentity
{
readonly Dictionary<ulong, string> ids = new Dictionary<ulong, string>();
public void Set(ulong connectionId, string playerId)
{
ids[connectionId] = playerId;
}
public void Remove(ulong connectionId)
{
ids.Remove(connectionId);
}
public bool TryGetPlayerId(ulong connectionId, out string playerId)
{
return ids.TryGetValue(connectionId, out playerId);
}
}
A player ID that a client simply sends can be faked. The sample uses the name typed in its menu, which is fine for a demo. A real game should check the ID on the host, for example by verifying a Steam ID against a Steam auth ticket.
Per-player data: SaveKit.Players #
SaveKit.Players holds each player's own data on the host: position, inventory, anything that belongs to one player rather than to the world. It is never null.
| Member | What it does |
|---|---|
For(playerId) |
The player's SaveData, created empty the first time you ask. Null for a null or empty ID. You can keep the object: a load refills it in place. |
ForConnection(connectionId) |
The same, found through SaveKit.Identity. Null when there is no identity or it does not name the player, with an SK141 warning in the Console once per connection. |
TryGetPlayerId(connectionId, out playerId) |
Asks SaveKit.Identity quietly, and catches its errors, which it reports as SK141. |
Has(playerId) |
Whether the player holds at least one value. True for a returning player, false for a new one. |
Remove(playerId) |
Forgets a player. The next save no longer writes them. |
GetPlayerIds(list) |
Every player with at least one value, in the order they were first seen. |
Clear() |
Forgets every player, which is what a new game wants. |
SaveData is the same class as SaveKit.Data, so Set and Get work the same way, with a category:
SaveData mine = SaveKit.Players.For(steamId);
mine.Set("position", transform.position, "Progress");
Vector3 back = SaveKit.Players.For(steamId).Get("position", spawnPoint, "Progress");
How it is stored. Player data goes into the host's save file beside the categories, under players.<player id>.<category>:
"data": {
"Progress": { ... },
"World": { ... },
"players": {
"alice": {
"Progress": { "position": ..., "rotation": ... },
"Inventory": { "inventory": ... }
}
}
}
- A save writes each player's values for every category it saves. A save of only some categories writes only those.
- Keep per-player values in Slot categories, such as Progress and Inventory. A value in a Global category would go into the host's global file, not into the slot.
- A slot load replaces the players' values for the categories it loads with what the file holds.
- The section is called
players, so no category may have exactly that name. Shipready refuses to start with a category calledplayers(SK153).
Players the save does not know. For(id) gives an unknown player empty data, so every Get returns the fallback you pass. That is how new players start from defaults. Use Has(id) when you need to tell a returning player from a new one.
Players who leave. Shipready keeps a player's data in SaveKit.Players until you call Remove or Clear, and every save writes it. Your game only has to write the player's latest values before their object goes. The sample does this when the player's object despawns on the host.
Applying the data is your game's job. Shipready keeps, saves and loads each player's data. Putting it back onto a player's object when they join is game code, because only your game knows what a player object is. The sample's CoopSaveBridge shows one way to do it.
The spawn hook: ISpawnHandler #
public interface ISpawnHandler
{
GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent);
void Despawn(GameObject instance);
}
Set it with SaveKit.SpawnHandler. Left at null, Shipready uses Instantiate and Destroy.
When Shipready calls it:
Spawn: during a load, once for each saved runtime object, before its state is restored. A runtime object is an instance of a prefab that was created during play and saved with its prefab ID. The prefab comes from the Prefab Registry. For an object at the root of the scene whose Saveable saves its position,positionandrotationare the saved ones, so a network spawn starts in the right place.parentis null. Shipready sets parents, and the exact transform, in its second pass. It also gives the new object its saved ID straight afterSpawnreturns, so the hook only has to make the object.Despawn: when a load removes a runtime object that the save replaces, for example in World Load Mode Restore Into Current Scenes.
What the hook must return. Return the object you made, with the prefab's Saveable on its root. If Spawn returns null, or the object has no Saveable on its root, that object is skipped with SK131, and the rest of the load goes ahead.
Spawns during play do not need the hook. The hook is only for what a load re-creates. Objects your game spawns during play are tracked automatically when their prefab has a Saveable on its root and is in the Prefab Registry.
Networked spawning on the host #
On the host, the hook should spawn through your network library, so that every client gets the object. The sample's NgoSpawnHandler handles three cases:
NetworkObject prefabObject = prefab.GetComponent<NetworkObject>();
if (prefabObject == null) return Object.Instantiate(prefab, position, rotation, parent);
NetworkManager manager = _manager;
bool listening = manager != null && manager.IsListening && !manager.ShutdownInProgress;
if (listening && manager.IsServer) return SpawnOnServer(manager, prefab, prefabObject, position, rotation, parent);
GameObject instance = Object.Instantiate(prefab, position, rotation, parent);
// Before a session starts the object waits for the server; on a client it stays local.
if (!listening) _pending.Add(instance);
return instance;
- On a running host, it instantiates and spawns in one step with
prefabObject.InstantiateAndSpawn(...), withdestroyWithSceneset to true. A prefab missing from the NetworkManager's Network Prefabs list is refused with a Console warning, so every prefab Shipready re-creates must be in both lists: Shipready's Prefab Registry and NGO's Network Prefabs list. - Before the session starts, which is when the host loads, the object is instantiated and kept as pending. It is spawned on the network when the server starts (see How the host loads before hosting).
- On a connected client, the object is only made locally. Only the host spawns networked objects. In practice a client never loads, so this case is a safety net.
Despawn despawns a spawned object on the host with NetworkObject.Despawn(true), and simply destroys one that was never spawned.
Pools #
A hook backed by a pool takes an object from the pool in Spawn and returns it to the pool in Despawn. Shipready gives the object its saved ID after Spawn returns, so the pool does not have to. Keep calling SaveKit.World.Despawned(obj) when your pool takes an object back during play, and SaveKit.World.Spawned(obj) when it hands one out, so an object waiting in the pool is never saved (see the pooled objects row in LimitsAndFAQ.md).
What your network library must sync #
Shipready restores state on the host only. It never sends anything over the network. Getting the restored state to the clients is the network library's job, so every value a client must see has to be network-synced by your game, for example with a NetworkVariable.
| What is saved | What the host has after a load | How clients see it in the sample |
|---|---|---|
| Runtime-spawned networked objects | Re-created through the spawn hook as networked objects | NGO sends spawned NetworkObjects to every client |
| Position and rotation | Set on the host's transform | A NetworkTransform with server authority |
Fields of your scripts (Field Picker or ISaveable) |
Set on the host's component | A NetworkVariable, as CoopItem.Kind uses |
| Each player's data | Applied to the player's object by your code | CoopPlayer's server-authoritative NetworkTransform and its NetworkList<int> inventory |
Values in SaveKit.Data, such as a shared day counter |
Back in SaveKit.Data on the host |
Not shown in the sample. Copy them into a NetworkVariable on the host. |
| Scene objects that the load switches off or destroys | Applied on the host | Not shown in the sample. It depends on how your library synchronises objects placed in a scene, so test it. |
If a transform is synced with owner authority, the owner keeps overwriting what the host restored. The sample uses server authority for players and items.
The pattern. Keep a plain copy of each synced value for the save, and push it into the network variable when the object spawns on the host. CoopItem saves its kind itself as an ISaveable:
public void CaptureState(SaveWriter w)
{
w.Write(KindKey, Kind);
}
public void RestoreState(SaveReader r)
{
Kind = r.Read(KindKey, kind);
}
A load on the host can make an item before the session starts, and NGO only accepts writes to a spawned object. So the item pushes its saved kind into the NetworkVariable as it spawns:
public override void OnNetworkSpawn()
{
_kind.OnValueChanged += OnKindChanged;
if (IsServer)
{
if (_kind.Value != kind) _kind.Value = kind;
}
else
{
kind = _kind.Value;
SaveKit.World.Despawned(gameObject);
}
ShowKind(_kind.Value);
}
The else branch matters too. On a client, NGO makes its own copies of the host's objects. SaveKit.World.Despawned(gameObject) keeps those copies out of the client's own world memory, because the world belongs to the host's save.
Other networking libraries #
The core is not tied to NGO. Any library that has a host, or a server, connects to Shipready through the same three interfaces and two habits. Your library's own documentation tells you which of its calls answer each question below.
ISaveAuthority: may this copy of the game save? Return true when it is not in a session, which is what lets the host load before hosting, and when it is the host or a dedicated server. Return false for a connected client. Set it withSaveKit.Authority.IPlayerIdentity: who is this connection? Map the library's number for a connection to the stable ID the player sent when joining, asPlayerIdMapabove does. Fill the map in where your host accepts a joining player, and remove the entry when the player leaves. If your library numbers connections with something other than aulong, convert it, or keep your ownulongper connection. Set it withSaveKit.Identity.ISpawnHandler: how does a saved object come back? On a running host, instantiate the prefab and spawn it through the library, so every client gets it. Before the session starts, instantiate it, keep it as pending, and spawn it once the server is running; keep such objects away from anything your library does to the objects it finds in a scene when a session starts. On a client, make the object locally only. Set it withSaveKit.SpawnHandler.- Per-player data. On
SaveEvents.Saving, write each connected player's data intoSaveKit.Players. When a player joins, read theirs back. When a player leaves, write theirs one last time, before their object is gone. - Sync. Every value clients must see goes through the library's own synced values, written on the host. Push values Shipready restored into them as each object spawns on the network.
The NGO sample is a worked example of all five, and the parts of it that do not depend on NGO's own calls carry over to any library.
The host-only model needs one machine that owns the world: a host or a server. Setups where no single machine owns the world, such as modes where every client has authority over its own objects, do not fit it.
1.0 is built and tested with NGO only. No other networking library is tested, and 1.0 has no samples for them.
The NGO sample #
The sample is a small host-and-join game. The host saves a world of spawned cubes, friends join and see it, and a friend who leaves and joins again gets their own position and inventory back. A short version of this walkthrough ships with it as Samples/CoopNGO/README.md.
What you need #
- Unity 6. The sample was tested in Unity 6000.6.
- Netcode for GameObjects 2.x, from the Package Manager. It installs Unity Transport. The sample was tested with NGO 2.13.3; its assembly accepts any 2.x version.
- TextMesh Pro's essential resources, for the menu's text. Import them with Window → TextMeshPro → Import TMP Essential Resources if the generator warns that they are missing.
- Either input system works: the Input System package or the old Input Manager.
- The sample makes its materials for the active render pipeline at runtime. It was checked in URP; HDRP gets automated tests only. Shipready's core has no rendering code.
The sample's scripts sit in their own assembly, RareGeometry.Shipready.Save.Samples.NGO, in Samples/CoopNGO. It compiles only when NGO 2.x is installed in Unity 6. The assembly uses versionDefines to define SHIPREADY_SAVE_NGO2 for com.unity.netcode.gameobjects versions from 2.0.0 up to, but not including, 3.0.0, plus defineConstraints on SHIPREADY_SAVE_NGO2 and UNITY_6000_0_OR_NEWER. In Unity 2022.3, with NGO 1.x, or without NGO, the sample does not compile, and nothing else in Shipready uses it. Its editor code is in a second assembly, RareGeometry.Shipready.Save.Samples.NGO.Editor, with the same conditions.
Building the sample #
The sample ships as scripts only. A menu command builds its scene and prefabs, because the Asset Store limits packages nested inside packages.
- Install Netcode for GameObjects 2.x with the Package Manager.
- Choose Tools → Shipready → Saves → Samples → Build Co-op NGO Sample. The menu item appears once NGO 2.x is installed.
- Press Build. The scene that is open now is closed first, with the usual offer to save it.
- When asked, press Add to put the sample scene in the build's scene list. Two builds need it.
The command builds everything in Assets/RareGeometryData/Shipready/Samples/CoopNGO/, outside Shipready's folder, so updating Shipready never touches it:
| File | What it is |
|---|---|
CoopNGO.unity |
The scene: a NetworkManager with Unity Transport, a camera, a light, the ground, a player spawn point, the item spawner and the sample's menu. It also holds Shipready's save menu when the menu prefab is in the project. |
Prefabs/CoopPlayer.prefab |
The player: NetworkObject, NetworkTransform (server authority), CoopPlayer and a capsule. No Saveable. |
Prefabs/CoopItem.prefab |
The item: NetworkObject, NetworkTransform, CoopItem, a Saveable with Position on, and a cube. |
CoopNetworkPrefabs.asset |
The Network Prefabs list the NetworkManager uses. It holds both prefabs. |
Data/CoopSampleSettings.asset |
The sample's own save settings: Save Folder Name CoopNGOSample, World Load Mode Restore Into Current Scenes, Autosave On Quit off. |
Data/CoopPrefabRegistry.asset |
The sample's Prefab Registry. It holds the item prefab. |
Data/CoopSceneRegistry.asset |
The sample's Scene Registry. It holds the sample scene. |
The NetworkManager has connection approval on and scene management off, because both copies of the game start in the same scene.
Running the command again rebuilds these files in place and keeps their GUIDs, so any changes you made to them are replaced. The sample saves into its own folder, %USERPROFILE%\AppData\LocalLow\<Company Name>\<Product Name>\CoopNGOSample, never into your game's saves. The sample's settings asset is not in a Resources folder, so Shipready may start by itself with your project's own settings first; the sample's menu then stops it and starts it again with the sample's settings. Run the sample on its own rather than inside your game.
For batch mode, the same build runs with -executeMethod RareGeometry.Shipready.Save.Samples.NGO.Editor.CoopSampleGenerator.Generate. It asks nothing, does not change the build's scene list, and fails the run when anything is wrong.
Trying it #
With two builds:
- Check that
CoopNGO.unityis in the build's scene list (File → Build Profiles, Scene List). - Build for Windows and start the build twice. One build plus Play in the Editor also works.
- In the first window, type a name and press Host new game. Windows may ask whether to let the game through the firewall. Allow it on private networks if a second computer is going to join.
- In the second window, type the host's address and a different name, then press Join. On the same computer the address is
127.0.0.1. From another computer on your network, use the host computer's address. The port is 7777, andaddress:portalso works. The sample connects directly by address, and playing over the internet would need port forwarding or a relay service, which the sample does not set up.
With Multiplayer Play Mode, if you have Unity's com.unity.multiplayer.playmode package: open Window → Multiplayer → Multiplayer Play Mode, switch on a second player, press Play, then host in one window and join in the other.
Controls: WASD or the arrow keys move. E picks up the nearest cube. Typing in a text field never moves the player.
What to check:
- The host starts a new game. 12 cubes appear around the item spawner.
- A friend joins and sees the same cubes. Both of you pick some up.
- The host saves. The friend sees no Save or Load button.
- The host presses Leave, which ends the session for everyone. Changes since the last save are lost, so save first.
- The host presses Load (before hosting) and picks the save. The host button changes to Host loaded save. The host presses it.
- The cubes are back where they were. The friend joins with the same name and gets their position and inventory back.
- Someone joins with a new name. They start at the spawn point with nothing.
A second player who tries to join with the name of a player already in the game is turned away, with the reason shown in their status line. Two builds on one PC share one global settings file, so both remember the same name: change it in the second window before joining.
A player whose connection dropped without leaving properly, for example after a crash, stays in the host's game until Unity Transport notices that the connection is gone, which takes 30 seconds with its default timeout. Until then, joining again with the same name is turned away.
What each script does #
All of them are in Samples/CoopNGO/Scripts, in the namespace RareGeometry.Shipready.Save.Samples.NGO.
CoopSaveBridge connects Shipready to a Netcode session. Two calls, once Shipready has started, are all a host needs:
CoopSaveBridge bridge = CoopSaveBridge.Install(NetworkManager.Singleton);
bridge.StartHost(); // or bridge.StartServer(); a client calls NetworkManager.StartClient()
- Install it on every peer, host and clients alike. It turns connection approval on, and connection approval is part of Netcode's configuration check, so a client whose setting differs from the host's cannot connect. On a client, the bridge's authority also makes
SaveKit.CanSavefalse. - Sets
SaveKit.Authority,SaveKit.IdentityandSaveKit.SpawnHandlerto anNgoSaveAuthority, anNgoPlayerIdentityand anNgoSpawnHandler. - Turns connection approval on and sets its own
ConnectionApprovalCallback, which records the player ID from each joining player's payload, turns away a second player with the ID of one who is still connected, and spawns each player where their saved data says. - Chains your own approval. If the NetworkManager already had a
ConnectionApprovalCallbackwhen the bridge was installed, the bridge keeps it and asks it first. When your callback turns a player away, or setsPendingto answer later, its answer stands. Otherwise the bridge adds its part: the player ID, and the spawn position and rotation when your callback did not set them. An exception in your callback turns the player away, with a Console warning. - On
SaveEvents.Saving, writes every connected player's position, rotation and inventory intoSaveKit.Players. Position and rotation go inPositionCategory("Progress"), and the inventory inInventoryCategory("Inventory"). Both categories must exist in the settings, and the defaults do. - Restores a player as their object spawns on the host, and captures a leaving player as their object despawns and again as they disconnect, so their latest data is kept whichever order Netcode reports the leave in.
- Spawns the objects that a load made before the session started, once the server is listening.
- Warns in the Console when a save loads while a session is running, which 1.0 does not support. Each player's own settings file may load at any time.
Starting a session. bridge.StartHost() and bridge.StartServer() prepare the session and then start the NetworkManager as a host or as a dedicated server; both return whether it started. Preparing forgets the last session's connections and keeps the objects a load made away from Netcode's start-of-session sweep (see How the host loads before hosting). If you start the NetworkManager yourself, call bridge.PrepareSession() just before. A plain NetworkManager.StartHost() is covered anyway, through the host's own approval, but a plain NetworkManager.StartServer() is not: use bridge.StartServer() for a dedicated server.
Its other public members: Find(manager), Uninstall(), IsInstalled, Manager, Authority, Identity, SpawnHandler, DefaultSpawnPosition, DefaultSpawnRotation, CapturePlayer(player), CaptureConnectedPlayers() and RestorePlayer(player). Install the bridge once Shipready has started, because stopping Shipready removes every save event handler, and call Uninstall() before SaveKit.Shutdown(). Uninstalling puts back the co-op hooks, the approval callback and the approval setting that were there before, and throws away pending objects nobody spawned. Install returns null, with a Console warning, when it cannot install.
This is how the bridge captures one player:
SaveData data = SaveKit.Players.For(playerId);
if (data == null) return false;
Transform t = player.transform;
data.Set(PositionKey, t.position, PositionCategory);
data.Set(RotationKey, t.rotation, PositionCategory);
data.Set(InventoryKey, player.CopyInventory(), InventoryCategory);
And this is how it looks a player up, falling back to the defaults for a player the save does not know:
position = _defaultSpawnPosition;
rotation = _defaultSpawnRotation;
items = NoItems;
if (string.IsNullOrEmpty(playerId) || !SaveKit.Players.Has(playerId)) return false;
SaveData data = SaveKit.Players.For(playerId);
position = data.Get(PositionKey, position, PositionCategory);
rotation = data.Get(RotationKey, rotation, PositionCategory);
items = data.Get(InventoryKey, NoItems, InventoryCategory) ?? NoItems;
return true;
NgoSaveAuthority is the ISaveAuthority for NGO, shown in full above.
NgoPlayerIdentity is the IPlayerIdentity for NGO. It maps a Netcode client ID to the stable player ID, filled in by the bridge's approval. It names the host from the payload in the host's own NetworkConfig.ConnectionData. Its members are TryGetPlayerId, TryGetClientId, Set, Remove, Clear and Count.
NgoSpawnHandler is the ISpawnHandler for NGO, described above. Besides Spawn and Despawn, it has SpawnPending(), DiscardPending() and PendingCount. DiscardPending() throws away the objects a load made that nobody is going to host, which a new game or joining someone else's game wants. On the host, it can only parent a networked object under another spawned NetworkObject, as Netcode requires. Otherwise the object stays at the scene root, with a warning. Netcode cannot spawn a switched-off object, so an item saved switched off is re-created switched off and stays a local object on the host; it is still saved. Switch it on and call SpawnPending() to put it on the network.
CoopPlayer is the player, a NetworkBehaviour. Its owner sends input to the host, and the host moves it. Its inventory is a NetworkList<int> of item kinds, written only on the host. On the host, OnNetworkSpawn asks the bridge to restore the player and OnNetworkDespawn asks it to capture them. ApplyState(position, rotation, items) and CopyInventory() are what the bridge uses, and PickUpNearest() picks up the closest cube within PickUpRadius. It is deliberately not a Saveable: its data is per player, so it goes through SaveKit.Players.
CoopItem is a cube, a NetworkBehaviour and an ISaveable. Its Kind lives in a NetworkVariable<int> and is copied to a plain field for the save, under the key KindKey ("kind"). On a client it keeps its copy out of the client's own world memory. FindNearest, CountSpawned and InstanceCount help the player and the spawner.
CoopItemSpawner scatters the starting cubes for a new game. When the server starts with no cubes in the scene, it spawns StartCount cubes (12 by default) around itself through SaveKit.SpawnHandler, so they are networked and saved as runtime spawns. When the host loaded a save first, the loaded cubes are already there, spawned or still pending in NgoSpawnHandler, and it adds nothing. Cubes a new game threw away with DiscardPending() do not count. SpawnItem(position, kind) spawns one cube.
CoopSampleMenu is the on-screen menu. It starts Shipready with the sample's settings and sets SaveKit.World.LoadMode to WorldLoadMode.RestoreIntoCurrentScenes. It installs the bridge and offers Host, Join (address and name), Load (before hosting), Save (while hosting) and Leave, with on-screen instructions. Host goes through bridge.StartHost(). Save and Load open Shipready's save menu when the scene has one, and otherwise use slot 1 directly. It hides Save and Load as described in Hiding the save buttons, and remembers the typed name in the global file. Join after a Load puts the loaded world away first, because a client plays in the host's world.
CoopConnectionPayload is the small JSON payload each player sends when joining, which holds their player ID. Create(playerId) makes the bytes for NetworkConfig.ConnectionData, and TryRead(bytes, out playerId) reads them back on the host. The payload comes from another computer, so reading it is careful:
- A payload longer than
MaximumPayloadBytes(256 bytes), or one that is not a JSON object, names nobody, so that player starts from defaults and is not kept in the save.Createnever makes a longer one. NormalisePlayerId(playerId)cleans an ID the same way on both sides: it removes control characters, trims spaces, and cuts the ID toMaximumPlayerIdLength(64) characters without splitting a character, such as an emoji or an accented letter, in two.
NetworkManager.Singleton.NetworkConfig.ConnectionData = CoopConnectionPayload.Create(steamId);
NetworkManager.Singleton.StartClient();
Two small helpers complete the sample. CoopInput reads the keys from whichever input system the project uses, and CoopMaterial makes a plain coloured material for the active render pipeline.
How the host loads before hosting #
The host loads while it is not yet in a session, so the network cannot spawn anything at that moment. The sample handles this in five steps:
- Start. Shipready runs with World Load Mode set to Restore Into Current Scenes, so a load restores into the scene that is already open. The bridge is installed, and the NetworkManager is not listening.
- Load. The host presses Load.
NgoSaveAuthoritysays yes, because the manager is not listening.SaveKit.LoadAsyncbrings backSaveKit.Playersand re-creates the saved cubes throughNgoSpawnHandler.Spawn. With no server running, each cube is instantiated and kept as pending, and its saved kind goes into its plain field. - Host. The host presses Host, and the menu calls
bridge.StartHost(). Before it starts the NetworkManager, the bridge prepares the session: it clears its player map and switches the pending cubes off. That keeps them away from Netcode's start-of-session sweep, which spawns the active NetworkObjects it finds. Older NGO 2.x versions may take such objects for objects placed in the scene, which clients cannot find. If the session cannot start, the cubes are switched back on. - Server started.
OnServerStartedswitches the cubes back on and spawns each one withNetworkObject.Spawn(true). Each cube pushes its saved kind into itsNetworkVariableas it spawns. The item spawner sees cubes in the scene and adds none. - Players. The host's own player spawns and gets its saved data back. Friends join, the bridge records their IDs and spawn positions, and NGO sends them the cubes.
The moments in the bridge's code. Preparing the session:
public void PrepareSession()
{
_identity.Clear();
_restored.Clear();
_players.Clear();
_spawnHandler.HidePending();
}
The host's own approval prepares the session too, so a game that calls NetworkManager.StartHost() itself is covered:
// The host approves itself as it starts: a new session, also when the game called
// NetworkManager.StartHost itself rather than through the bridge.
if (isHost) PrepareSession();
And once the server is listening:
void OnServerStarted()
{
if (!_installed) return;
_spawnHandler.SpawnPending();
}
A dedicated server has no host approval of its own, which is why it has to start through bridge.StartServer(), or call bridge.PrepareSession() first.
Starting a new game #
A co-op host starts a new game in the scene that is already open, so the old world has to go before hosting. The sample's Host new game does it with three calls:
void StartNewGame()
{
if (_bridge != null) _bridge.SpawnHandler.DiscardPending();
SaveKit.World.ClearAll();
SaveKit.Players.Clear();
}
DiscardPending()throws away any items a load made that are still waiting to be hosted.SaveKit.World.ClearAll()forgets scene memory, destroyed lists and spawned objects, andSaveKit.Players.Clear()forgets every player's data.- They leave
SaveKit.Data, the playtime and the slot name alone. The sample keeps nothing else there.
In your own game, SaveKit.NewGame() is the fuller choice and works for a new game in the open scene too. It does everything ClearAll and Players.Clear do, and also empties every Slot category in SaveKit.Data, so values such as a day counter start again, and resets the slot name, location, summary lines, playtime and autosave timer. It keeps Global categories. What NewGame cannot do is reset your scene's objects: they keep whatever state they have, and the next slot save or quicksave captures them as they are (Shipready's own autosaves leave the open scene out until then). So put them back to their new-game state yourself; the sample, for example, starts every session with no cubes in the scene and lets its item spawner scatter new ones. Still call DiscardPending() for items a load made. Make a slot save or a quicksave before the host leaves that scene, or its changes since NewGame are not remembered when the game comes back to it (see Starting a new game in the Manual).
Adapting it to your game #
- Copy what you need. Copy the scripts out of
Samples/CoopNGO/Scriptsinto your own folder and namespace, because a Shipready update replaces the sample folder.CoopSaveBridge,NgoSaveAuthority,NgoPlayerIdentity,NgoSpawnHandlerandCoopConnectionPayloadare the reusable parts.CoopPlayer,CoopItemand the menu are examples. - Install after Shipready starts, on every peer. Call
CoopSaveBridge.Install(NetworkManager.Singleton)once Shipready has started, which with Initialise Automatically on is already the case in your first scene'sAwake, and before the host or client starts. Install it on the host and on every client. CallUninstall()beforeSaveKit.Shutdown(). - Load into the open scene, before hosting. Set World Load Mode to Restore Into Current Scenes, in the settings asset or with
SaveKit.World.LoadMode. Open the gameplay scene, wait forSaveKit.LoadAsyncto finish, and only then callbridge.StartHost(), orbridge.StartServer()for a dedicated server. If you start the NetworkManager yourself, callbridge.PrepareSession()just before. - Send a stable ID. Set
NetworkConfig.ConnectionData = CoopConnectionPayload.Create(steamId)before starting the host or the client, and verify the ID on the host. The payload is limited to 256 bytes and the ID to 64 characters. - Chain your approval checks. Set your own
ConnectionApprovalCallback, with checks such as auth tickets or a full server, before you install the bridge. The bridge keeps it, asks it first, and lets its answer stand when it turns a player away or setsPending. Do not set another callback while the bridge is installed, because that would replace the bridge's. - Save your player data. Change
CapturePlayerand the lookup to write and read your own player values, in Slot categories. Keep the Saveable off your player prefab: players come back throughSaveKit.Players, not as saved world objects. - Register every prefab twice. Every prefab Shipready re-creates needs a Saveable on its root, an entry in Shipready's Prefab Registry, and an entry in the NetworkManager's Network Prefabs list.
- Sync what clients must see. Use
NetworkVariable,NetworkListand server-authoritativeNetworkTransform, and push restored values inOnNetworkSpawnon the host, asCoopItemdoes. On clients, callSaveKit.World.Despawned(gameObject)for networked copies of saved objects. - Gate your menu. Show Save and Load only when
SaveKit.CanSaveandSaveKit.CanLoadallow it, and offer Load only on the way to hosting, never before joining. - Start new games the right way. Call
SaveKit.NewGame(), orSaveKit.World.ClearAll()andSaveKit.Players.Clear()as the sample does, plusbridge.SpawnHandler.DiscardPending(). For a new game in the open scene, also put the scene's objects back to their new-game state yourself (see Starting a new game). - Capture scenes you unload yourself. If the host changes scenes during a session through NGO's scene manager, call
SaveKit.World.CaptureScene(scene)on the host before a scene unloads, as with any scene loader of your own. - Test the whole loop with two builds. Save, quit, load, host, join, leave and rejoin, then join with an unknown ID. On a client,
SaveKit.Save(1)should returnHostOnly.
Limits #
- There is no loading during a session. The host loads before friends join.
- Only Netcode for GameObjects 2.x is shown and tested, with NGO 2.13.3. Other libraries can use the three interfaces, but 1.0 has no samples for them.
- A dropped connection lingers. A player whose connection dropped stays in the game until Unity Transport's disconnect timeout, 30 seconds by default. Rejoining under the same ID is turned away until then.
- Switched-off items stay local. An item saved switched off is re-created switched off and stays a local object on the host, still saved, until it is switched on and
SpawnPending()runs. - Shipready never syncs anything itself. State is restored on the host, and your network library shows it to clients.
- The sample's player IDs are typed names. Use an ID that cannot be faked in a real game.
- Encryption is not anti-cheat. In co-op the host's save is the authority anyway (see LimitsAndFAQ.md).
Contact #
Report a bug with the bug report form, ask a question in Discussions, email the address in Tools > Shipready > Saves > Help or visit https://raregeometry.github.io/.