Skip to content

Save and restore one context

TunalPersistence is the context-level orchestration bridge. Put it on the same GameObject as the TunalContext; its RequireComponent enforces a context host. The supplied context foundations already include persistence configuration—inspect that component before adding a duplicate.

Configure the owner and scope

  1. Assign Context and a stable Context ID (component default main). Keep Require Matching Context ID enabled unless your integration deliberately supports importing another identity.
  2. Assign Profile Catalog when saving profile selections.
  3. Expand Select State To Save and review each section, not just the top-level checkbox.
  4. For separate visual rigs, set Presentation Root or Presentation Group. Root takes precedence; group is used when root is empty. Empty scopes use conventional owned-hierarchy discovery.
  5. Assign explicit Cloud/Celestial Light/Sky/Star targets only when needed, ensuring they belong to the context/scope.
  6. Initialize in Play Mode and inspect validation before using Save Slot / Load Slot.

Persistence scopes are not permission to capture another context's presentation. Ambiguous or wrong explicit targets are configuration errors; a scene-wide “first controller found” is not a reliable save target.

Saved sections and defaults

Section Default selection and relevant options
Time Enabled: source mode, simulated elapsed clock, pause, stored game-minute speed, rate mode, solar-day duration/scale, UTC offset, display hours
Calendar Enabled: mode, definition, starting date/epoch; transition duration off by default
Astronomy Enabled: profile, observer location, solar-time correction
Day Phases / Lunar Enabled: profile references
Seasons Enabled: profile reference and fallback latitude
Clouds Enabled: live weather and offset; profile selection off by default
Celestial Light Enabled: unified controller's runtime stylized override state
Sky Disabled; if enabled, quality and Sun diameter selected
Stars Disabled; if enabled, tint/intensity/rotation selected
Lifecycles Disabled; explicit instance registration required

An absent optional module is normal. An enabled but unready module can produce an omission warning. The save is not a dump of every Inspector field: nebula settings, all rendering material contents, separate Moon controller state, randomizer history, gameplay objects, and UI selection are not implied by these section names.

Capture without writing a file

Attach ContextSnapshotMemory to an active GameObject, assign its persistence component, and call Capture, change time, then Restore:

ContextSnapshotMemory.cs
using Sital.Tunal.Persistence;
using UnityEngine;

namespace TunalExamples
{
    public sealed class ContextSnapshotMemory : MonoBehaviour
    {
        [SerializeField] private TunalPersistence persistence;
        private Snapshot captured;

        public void Capture()
        {
            if (persistence == null || persistence.Context == null ||
                !persistence.Context.Initialize()) return;
            var result = persistence.Capture(out Snapshot candidate);
            Report(result);
            if (result.success) captured = candidate;
        }

        public void Restore()
        {
            if (persistence == null || captured == null) return;
            var validation = persistence.ValidateRestore(captured);
            Report(validation);
            if (validation.success) Report(persistence.Restore(captured));
        }

        private void Report(PersistenceResult result)
        {
            if (!result.success) Debug.LogError(result.error, this);
            foreach (string warning in result.warnings)
                Debug.LogWarning(warning, this);
        }
    }
}

Capture(out Snapshot) returns selected data; failed capture does not replace the example's previous snapshot. ValidateRestore(snapshot) preflights without mutating the context. Restore(snapshot) still performs its own validation. Do not modify the scene between preflight and restore and assume that earlier validation is a transaction lock.

For your backend, StateSerializer.ToJson(snapshot) and FromJson(json) convert portable data; malformed/empty input can throw. Keep Unity capture/restore on the main thread and handle parsing/transport failures. Storage explains schema and restore boundaries.

Local save and load example

Choose Local Folder and Slot on persistence (defaults Tunal and autosave). Attach this example outside switchable roots and bind UI buttons to Save/Load:

ContextSaveButtons.cs
using Sital.Tunal.Persistence;
using UnityEngine;

namespace TunalExamples
{
    public sealed class ContextSaveButtons : MonoBehaviour
    {
        [SerializeField] private TunalPersistence persistence;
        private bool saving;

        private bool Ready()
        {
            return persistence != null && persistence.Context != null &&
                   persistence.Context.Initialize();
        }

        public void Save()
        {
            if (saving || !Ready()) return;
            saving = true;
            StartCoroutine(persistence.SaveLocalConfirmed(result =>
            {
                saving = false;
                Report(result);
            }));
        }

        public void Load()
        {
            if (!saving && Ready()) Report(persistence.TryLoadLocal());
        }

        private void Report(PersistenceResult result)
        {
            if (!result.success) Debug.LogError(result.error, this);
            foreach (string warning in result.warnings)
                Debug.LogWarning(warning, this);
        }
    }
}

Keep the coroutine host active through completion, disable overlapping operations, and reset your own UI state if the host is destroyed. The example uses confirmed saving, including the browser synchronization phase on WebGL. Load remains synchronous. A successful save can have warnings; inspect them before claiming that every desired section was captured.

Do not share a local filename between independently saved contexts. Existing data owned by a different context is refused rather than silently overwritten. Use different slots or WorldPersistence.