Saving objects the game spawned

Persist.Spawn, SaveInstances and LoadInstances — remember the objects a game created from a prefab while it ran, and bring them back without duplicating them.

Unity objects NexusForge Persistence 1.0.0 Updated

The thing nothing else can supply#

An object the game created from a prefab is an ordinary scene object once it exists, so its parts can be saved the usual way. What is missing is which prefab to make again and which instance this is — and Unity's "what asset is this from?" question exists only in the editor. PersistKit records both when the object is created.

Spawning with an identity#

csharp
GameObject enemy = Persist.Spawn(class="tok-str">"enemy-prefab", class="tok-str">"enemy-3", parent: spawnPoint);
class="tok-com">
// later, at a checkpoint:
Persist.SaveInstances(class="tok-str">"enemies", allEnemies);
class="tok-com">
// on load:
var restored = new List<GameObject>();
Persist.LoadInstances(class="tok-str">"enemies", parent: null, into: restored);
  • Persist.Spawn(prefabKey, instanceId, parent) makes the instance from the prefab registered under that key, gives it a PersistKitIdentity with the id you chose, and marks it with PersistKitSpawned.
  • The id is yours to choose and has to be stable: the same id next run finds the same instance. Build it from the data that created the object — "enemy-" + index — not from a random number.
  • Persist.SaveInstances writes the set (each instance's prefab key and id) under one key, and saves each instance's own remembered state under <key>.<instanceId>, so the parts you ticked come back with it.

Loading never duplicates#

SituationWhat happens
An object with that id is already in the loaded scenesIt is reused, not created a second time
A saved instance is not there at allIt is made again from its prefab
The prefab is not in this buildReported (PK-REF-005) and skipped; the save file is left alone
Two objects claim the same idReported (PK-REF-003); nothing is picked at random

Loading the same save twice is therefore safe, which is what makes a "continue" button that can be pressed twice behave.

An object the game instantiated itself#

Object.Instantiate does not tell PersistKit anything, so that object has no prefab record and is refused with PK-REF-007 and a sentence saying how to make it rememberable: create it with Persist.Spawn, or save its components under keys of your own. Being quietly unrememberable is worse than being told.

Next#

Something wrong on this page? Every page here describes behaviour that is checked in the repository. If a page and the package disagree, the package wins.

Report a documentation problem · Error codes · Platforms and limitations