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.
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#
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 aPersistKitIdentitywith the id you chose, and marks it withPersistKitSpawned.- 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.SaveInstanceswrites 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#
| Situation | What happens |
|---|---|
| An object with that id is already in the loaded scenes | It is reused, not created a second time |
| A saved instance is not there at all | It is made again from its prefab |
| The prefab is not in this build | Reported (PK-REF-005) and skipped; the save file is left alone |
| Two objects claim the same id | Reported (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