Skip to content

Persistence

Maturity: Mature · Documentation baseline: 0.4.4 · Updated 2026-10-18

The module originated in 0.3.9. The current Runtime API is stable and supports schema v2, typed business-data Containers, and StateGraph ContextFrame persistence. The older ICoCoContext adapter path remains supported for compatibility.

Persistence writes local JSON save slots. A save document contains slot metadata, per-entity Context records, and the active Container section.

See the v0.4.4 package guide and the known limitations.

PersistenceSession.Capture(slot)
├─ PersistenceContextRegistry.CaptureSection()
└─ PersistenceContainerHost.CaptureActiveSection()
↓
PersistenceSaveDocument (schema v2)
↓
temporary JSON → replace target → recovery backup on replacement failure

The module has four runtime MonoBehaviour types:

Component Responsibility
PersistenceHost Optional save/load entry; configures slots, directory and the ContainerHost reference.
PersistenceContainerHost Global authority for business-struct tables, one table per type.
PersistenceContext Stable entity identity and Context capture/restore, including the same-object StateGraph Host.
PersistenceContainer Binds a business GameObject to a locked type, ID and initial candidate.
Global persistent object
├─ PersistenceHost save/load entry; references ContainerHost
└─ PersistenceContainerHost authoritative tables
└─ ChestData["chest-01"]
↑ type + ID binding
Chest prefab instance
├─ PersistenceContainer ChestData + chest-01 + initial candidate
└─ Chest same-object business script → typed handle
Graph actor (existing setup)
├─ CoCoStateGraphHost
└─ PersistenceContext stable entity ID + ContextFrame

Graph-only projects keep their existing components and static API; no new component is required. PersistenceHost is optional. Its SaveGame(int slotIndex = -1) / LoadGame(int slotIndex = -1) delegate to the same static flow, slots and Session. Omitting a slot uses CurrentSlotIndex.

PersistenceSaveDocument.CurrentSchemaVersion is 2. The document contains:

Field Meaning
schemaVersion Save schema version. Versions newer than the package supports are rejected.
metadata Slot index and save metadata/timestamps.
contextSection Records keyed by stable entity ID.
containerSection Business-struct records keyed by type and ID (Container format v1).

Older Graph documents retain metadata and Context records when normalized to schema v2.

PersistenceFileStore writes savegame_slot_<index>.json under Application.persistentDataPath, unless SaveDirectoryOverride is set. It serializes with Newtonsoft.Json to a .tmp file and then replaces the target. During replacement, a .bak file is used as a recovery path; if the main file is missing on read, an available backup is accepted. Successful replacement cleans the transient backup.

PersistenceSaveLoadSystem exposes the simple slot API:

PersistenceSaveLoadSystem.SaveGame(0);
bool loaded = PersistenceSaveLoadSystem.LoadGame(0);

MaxSaveSlots defaults to 3, and CurrentSlotIndex defaults to 0. Invalid slots and I/O failures are logged and rejected. The file format is local JSON; the module does not provide encryption, cloud synchronization, conflict resolution, or multi-process locking.

Add PersistenceContext to every entity whose Context should be saved. It owns a serialized stableEntityId and optional prefabKey.

  • scene instances receive persistent Editor-authored IDs;
  • runtime-only instances receive an RT_... ID when needed;
  • the registry indexes live contexts by that stable ID;
  • a later registration can consume a matching record from the pending document.

Copied prefabs and dynamically spawned objects still require the project to ensure the intended identity policy. Persistence does not spawn missing scene objects or resolve a prefab key by itself.

Enable Persistence restore for each supported Operator in the Host’s Operators list before startup. It is off by default and independent of Temporal recovery. LocomotionOperator, AnimAutoOperator, and CameraOperator support this path. Ordinary execution and Context capture continue while recovery is disabled; restore retains that Operator’s current Outcome values. Graph and [Memory] state restore from the target snapshot, then Derived values rebuild. See Usage examples and Camera.

When PersistenceContext finds a CoCoStateGraphHost on the same GameObject, StateGraph is the preferred capture path:

  1. TryCapturePersistencePayload captures the committed ContextFrame payload.
  2. The payload is stored in a record discriminated as CoCoFlow.StateGraph.ContextFrame.
  3. Loading validates that discriminator, the payload, stable identity, and the Host lifecycle before applying it.
  4. Running or Suspended Hosts apply immediately through TryApplyPersistencePayload.
  5. Created or Stopped Hosts defer the apply until the Host becomes live.
  6. Disposed Hosts, missing same-object Hosts, malformed payloads, and rejected Host diagnostics fail closed.

The pending-document apply token prevents the same StateGraph record from being consumed twice by one live context during that load. This payload is durable save data and is separate from the same-session Temporal ring representation.

LoadGame performs two logical phases:

  1. Read, deserialize, migrate, and install the document as PersistenceSession.PendingDocument.
  2. Apply Containers and all currently registered Context records.

Contexts that register later check the pending section and apply their matching record. StateGraph records may additionally wait for a Created or Stopped Host to enter a live lifecycle. Call PersistenceSession.ClearPendingDocument() when the project no longer wants late registrants to consume the loaded save.

If no CoCoStateGraphHost is present, PersistenceContext tries the registered IPersistenceContextAdapter implementations against an ICoCoContext on the same object. Since 0.4.1, the package no longer ships built-in Character or Item adapters: the registry is a pure extension point, and a host that needs Context capture implements IPersistenceContextAdapter and registers it through PersistenceContextAdapterRegistry itself.

This path remains supported. It captures selected typed facts into PersistenceContextRecord; it is not treated as deprecated or as an API that must be replaced.

PersistenceContainerHost owns one table per business struct. Data type + ID identifies a row: matching types and IDs share data, while different types may reuse an ID. Existing rows, including loaded saves, take precedence over a first-registration candidate. Quests, rewards and random drops belong to business scripts.

On the global PersistenceHost, configure:

  • Container Host: drag the enabled global ContainerHost here. Leaving it empty uses global registration and also supports Graph-only scenes.
  • Max Save Slots: default 3; Initial Slot: default 0, indexed from zero.
  • Save Directory: empty uses Application.persistentDataPath; relative folders resolve against it, and absolute paths are used directly.
  • Path Preview / Effective Paths: resolved absolute directory and initial/current slot file. Open Folder creates the directory if needed and opens it; Copy Path copies the directory. Preview alone creates nothing.

Enable Debug Mode before Play to save and load in the host project’s Assets/DebugSaves/. The Inspector disables but retains Save Directory. Files are created on an actual save, which refreshes the Project window; enabling the mode neither saves automatically nor moves old files. Player always uses normal directory configuration.

Enable one global PersistenceHost before business scripts. It applies its configuration to the shared static API; Host and static calls use the same save/load flow. Disabling it restores previous static settings. Configuration fields are locked during Play; runtime values and the connected ContainerHost remain visible. Without it, the existing static configuration remains supported.

The ContainerHost Inspector shows active status, bound component count, table count, total rows and per-type row counts. Paths and slots belong to PersistenceHost. Re-enabling the same ContainerHost retains changes since its last load; initialization only applies a new pending load.

Use ordinary non-generic structs marked [Serializable, PersistenceData], including custom nested structs. Only public writable instance fields are stored; properties, static, readonly and [NonSerialized] fields are not. Private [SerializeField] data fields are unsupported.

Add PersistenceContainer to the Chest prefab. In its Inspector, choose ChestData, set a nonempty ID such as chest-01, and edit initial values if desired. The picker shows searchable short type names, with namespace/assembly details for collisions. It filters normal Player assemblies, excluding Editor-only and test assemblies; see the DLL limitation below. Nested initial fields and collections support normal Undo and prefab overrides. Generic API calls do not select or change the locked type.

Here business Awake supplies a candidate instead of the Inspector’s initial values:

using System;
using CoCoFlow.Runtime.Modules.Persistence;
using CoCoFlow.Runtime.Modules.Persistence.Container;
using UnityEngine;
[Serializable, PersistenceData]
public struct ItemStackData
{
public string Key;
public int Count;
}
[Serializable, PersistenceData]
public struct ChestData
{
public int Coins;
public ItemStackData Bonus;
public ItemStackData[] Items;
}
[RequireComponent(typeof(PersistenceContainer))]
public sealed class Chest : MonoBehaviour
{
private PersistenceContainer _container;
private PersistenceContainerHandle<ChestData> _data;
private void Awake()
{
_container = GetComponent<PersistenceContainer>();
_container.SetInitialData(new ChestData
{
Coins = UnityEngine.Random.Range(1, 6),
Bonus = new ItemStackData { Key = "potion", Count = 1 },
Items = Array.Empty<ItemStackData>()
});
}
private void Start()
{
_data = _container.GetHandle<ChestData>();
}
public int TakeCoins(int requested)
{
if (requested <= 0)
return 0;
ref ChestData data = ref _data.Value;
int taken = Mathf.Min(requested, data.Coins);
data.Coins -= taken;
return taken;
}
}

Bonus is plain nested data in the ChestData row, not another Container or a link. Items may also be List<ItemStackData> with System.Collections.Generic. Supported values are bool, ordinary integers, float/double, char, string, enums, marked structs, and one-dimensional arrays or List<T> of supported leaf/struct values. Null strings/collections stay distinct from empty values. Classes, Unity object references, delegates, pointers, Dictionary, multidimensional/jagged arrays and collections of collections are unsupported.

Randomness and coin removal above belong to Chest. A later Chest with the same type and ID receives the existing row; its candidate is ignored. Use different IDs for independent instances, preparing runtime IDs with SetId(string) in business Awake before binding. Initial arrays/lists are copied, so changing a candidate later does not modify the live row.

Bootstrap one global ContainerHost before any business Container enables and keep it alive for the required data lifetime. Default execution orders are ContainerHost -10000, PersistenceHost -9000, Container 10000. There is no automatic Host creation, wait, retry or fallback.

The order is business Awake prepares values → Container OnEnable registers → business Start gets the handle. Preserve it when overriding script execution order; do not first get a handle in ordinary business OnEnable. OnDisable unbinds the component but retains its row. Re-enabling binds the existing row without resetting it or rerunning Awake/Start.

PersistenceContainer exposes Id, DataType, IsBound, SetId(string), SetInitialData<T>(in T), GetHandle<T>() and TryGetHandle<T>(out PersistenceContainerHandle<T>) (T : struct). Setters require an unbound component. Invalid types, mismatched T and empty IDs are errors. GetHandle before binding throws; TryGetHandle returns false when unbound, but invalid types remain errors.

A handle exposes Id, IsValid and ref T Value. var copy = handle.Value copies the struct; scalar changes to that copy do not write back. Arrays/lists retain C# shallow-reference semantics. Modify a List’s struct element by reading, changing and assigning it back. Keep a ref only for one synchronous operation, never across load/await/yield. Keep handles across loads and resolve Value again, rather than caching refs or collection references.

Disabling a component leaves its handle valid while the Host row exists. Changing its ID while disabled does not retarget an old handle or move/delete the old row; get a new handle after registration. Default handles, destroyed Hosts and missing rows are invalid; Value throws instead of creating data.

Pure-code access explicitly references the ready ContainerHost and calls GetOrCreate<T>(string id, in T initialData) or TryGet<T>(string id, out PersistenceContainerHandle<T> handle). Only a missing row adopts the candidate; TryGet does not create one. Writes need no Commit, MarkDirty or event command.

The overall save remains schema v2. Only containerSection has its own formatVersion: 1, with records { typeId, id, data }. Type IDs use AssemblySimpleName:Namespace.TypeName, without assembly versions. Type/assembly renames have no automatic migration; missing fields use defaults and obsolete fields are ignored.

Loading validates and prepares tables before replacing the live tables. A handle resolves the restored row on its next access. Missing rows with active bindings are recreated from their components’ candidates in registration order, without rerunning Awake or gameplay initialization. Missing rows without active bindings are removed and their old handles become invalid.

Old Graph saves with absent, null or empty Container sections remain readable. Old Container gameplay data is discarded with a warning and is not migrated; Graph data is preserved. Unknown new versions/types, duplicate composite keys and malformed data are rejected. StateGraph APIs and apply timing remain unchanged.

Actual Player save/load and stripping compatibility have not been validated for 0.4.4. Container linker metadata is supplied, but Editor verification does not establish target-backend or stripping compatibility.

The following issues were accepted in PR #71 and remain unfixed in this release:

Issue Current limitation
BUG-111 A failed load may leave a pending snapshot that later registrations can consume. Failure does not guarantee pending state was cleared.
BUG-112 ../ may resolve outside the default save directory. Relative-path configuration is not a directory sandbox.
BUG-113 Closed generic root structs fail when saving, despite passing initial validation. Use ordinary non-generic root structs.
BUG-114 Business types in precompiled DLLs may be omitted from the type picker and stripping metadata.
  • Saves capture logical Context and Container data, not a complete Unity scene or arbitrary component graph.
  • A valid stable ID policy is required for entities that must survive reload.
  • Save/load calls are synchronous at the file API boundary.
  • Backup handling protects file replacement; it is not a versioned backup history.
  • “Mature” means the public Runtime API and schema-v2 responsibilities are stable and usable. It does not claim zero defects, optimal serialization throughput, or store-grade save infrastructure.