Usage examples
These examples target v0.4.5. The current package documentation defines the contracts.
Typed Persistence data
Section titled “Typed Persistence data”Use a global PersistenceContainerHost for business-struct tables and put a
PersistenceContainer beside its business script on the prefab. Lock the type
and ID in the Inspector. Business Awake prepares initial data, Container OnEnable
registers, and business Start calls GetHandle<ChestData>(). Existing rows win
against candidates; matching type + ID shares data. Modify the row through a ref:
ref ChestData data = ref _data.Value;data.Coins += 1;See the complete non-generic struct and business script
for setup, nested data, arrays/List and handle lifetime. PersistenceHost optionally
configures slots, directories and Editor Debug Mode. Graph-only projects keep their
existing API and components. Player save/load and stripping remain unverified;
see known limitations.
StateLogic, Config, and Memory
Section titled “StateLogic, Config, and Memory”Declare reads and writes with [Intent] and [Operation] properties. Declare state data with [Config] and [Memory] public instance fields:
using CoCoFlow.Runtime.Core;using CoCoFlow.Runtime.Locomotion.Contracts;
[CoCoState("Move")]public sealed class MoveLogic : CoCoStateLogic, ICoCoStateUpdate{ [Intent] public InputIntentData Input { get; set; } [Operation] public ILocomotionSection Movement { get; set; }
[Config] public float Speed = 6f; [Memory] public float ActiveSeconds;
public void Update(CoCoStateExecutionContext context) { ActiveSeconds += (float)context.TickFrame.DeltaTime; Movement.UseGravity = true; Movement.GravityScale = 1f;
for (int index = 0; index < Input.Count; index++) { if (Input.TryGet(index, out RawInputRecord record) && record.Action == CoCoFixedString64.FromString("Move") && (record.Phase == RawInputPhase.Performed || record.Phase == RawInputPhase.Held)) { Movement.MoveX = record.ValueX * Speed; Movement.MoveZ = record.ValueY * Speed; } } }}Add a Move State in the Graph Editor and configure Speed for each state. States using the same Logic have independent configuration. Missing overrides use field initializers; 0 and false are valid overrides. ActiveSeconds is captured with Context and restored with activation state through save/load and Temporal restore.
Memory fields must remain unmanaged. Standard Config has a separate type
contract: supported scalars, pure data structs, and one-dimensional arrays or
List<T> of those elements. This runtime generic binding path remains unverified
in an IL2CPP Player. StateLogic must implement ICoCoStateUpdate; 0.4.5 neither
supplies an empty Update nor adds a preflight check for the missing interface.
Minimal Config collection example
Section titled “Minimal Config collection example”This complete declaration uses the standard binding path; no custom Config, Schema or Factory is needed. It shows a scalar array, struct array and struct List. Keep it in the project’s pure graph-author assembly, as described in the Compiler guide.
using System;using System.Collections.Generic;using CoCoFlow.Runtime.Core;
[Serializable]public struct ConfigWindow{ public float StartSeconds; public double EndSeconds; public bool Enabled;}
[CoCoState("ConfigCollections")]public sealed class ConfigCollectionsLogic : CoCoStateLogic, ICoCoStateUpdate{ [Config] public float[] Speeds = { 2.5f, 6f }; [Config] public ConfigWindow[] Windows = { new ConfigWindow { StartSeconds = 0.25f, EndSeconds = 1d, Enabled = true } }; [Config] public List<ConfigWindow> ExtraWindows = new List<ConfigWindow>(); [Memory] public double ActiveSeconds;
public void Update(CoCoStateExecutionContext context) { ActiveSeconds += context.TickFrame.DeltaTime; }}Add ConfigCollections in the StateGraph Editor. Initialize a null collection
explicitly if needed; use Unity’s native collection controls to add/remove,
drag to reorder, and edit each struct’s fields. Here ExtraWindows starts empty.
An explicit empty collection overrides an initializer; an omitted override keeps
the Logic constructor default. Config is independent per State and runtime Logic
instance. ActiveSeconds is Memory and keeps the unmanaged contract.
Typing 2. keeps that intermediate text in the numeric control. Confirmation
or focus loss updates the draft; Save writes the State name, Logic and Config
together, and Discard abandons the draft. Reset clears the whole Config’s
overrides back to constructor defaults in the draft; there is no field or
collection Reset. Switching selection prompts to save, discard or cancel.
See the Editor guide
for Undo/Redo and refresh behavior.
Minimal hit example
Section titled “Minimal hit example”The event carries a target ID, hit ID, and damage amount. Keep these shared payloads in a pure C# contracts assembly:
public struct HitMail{ public int TargetId; public int HitId; public int Damage;}
public struct HitReceipt{ public int TargetId; public int HitId; public int AppliedDamage; public int Health;}Put this Adapter under the receiving Host and reference it in Event Adapters. The Host owns subscription and cleanup; Accept only filters the payload. Components behind a nested Host belong to that nested Host.
using CoCoFlow.Runtime.Core;using UnityEngine;
public sealed class HitInboxAdapter : MonoBehaviour, ICoCoEventInboxAdapter<HitMail>{ [SerializeField] private int actorId = 1;
public bool Accept(in HitMail payload) => payload.TargetId == actorId;}Place this Logic in a pure C# assembly with noEngineReferences: true. Make Damage an always-active root State in one Layer, with no outgoing transition, and give it sole responsibility for handling hits:
using CoCoFlow.Runtime.Core;
[CoCoState("Damage")]public sealed class DamageLogic : CoCoStateLogic, ICoCoStateUpdate{ [Config] public int Armor = 2; [Memory] public int Health = 100;
public void Update(CoCoStateExecutionContext context) { if (!context.Inbox.TryGetBatch<HitMail>(out var mails)) return;
for (int index = 0; index < mails.Count; index++) { if (!mails.TryRead(index, out var mail)) continue; int damage = System.Math.Max(0, mail.Damage - Armor); int applied = System.Math.Min(Health, damage); Health -= applied;
var receipt = new HitReceipt { TargetId = mail.TargetId, HitId = mail.HitId, AppliedDamage = applied, Health = Health }; context.Outbox.Publish(in receipt); } }}Here Health is activation Memory, committed with Context; it resets on reactivation. Keep the root active to retain health across child-state changes. Actor-wide health that must outlive this activation belongs in a project-owned Context/Operation design.
An external Unity hit source can send var hit = new HitMail { TargetId = 1, HitId = 7, Damage = 10 }; CoCoEventBus.Publish(ref hit);. With default Armor and Health, the next accepted Tick freezes the inbox, applies 8 damage, and commits Health 92. Only then does the ordinary EventBus publish HitReceipt with AppliedDamage = 8 and Health = 92. A failed or cancelled Tick commits neither the new health nor its receipt. Logic never calls the EventBus directly and needs no hit Intent, send Adapter, or per-event Binding.
Mailbox boundaries
Section titled “Mailbox boundaries”- Direct mail is accepted only while Running. Suspended and Temporal Previewing drop arrivals; lifecycle input-authority changes clear pending direct mail. Stop/Dispose removes subscriptions.
- Each event type has an incoming queue bounded by
eventLaneCapacity. Full queues retain existing mail and drop new arrivals without faulting the Host. A Host can bind multiple Adapters and event types; filters for one type are ORed, so one bus delivery enters that Host once. Separate Publish calls remain separate mail. - Tick freeze separates arrivals from the current batch. Later arrivals wait for a later Tick.
TryGetBatchreturns an empty registered batch with Count 0, or false for an unknown type. Reads do not consume mail; all views expire after the State callback, and the next Tick replaces unread mail. Do not process the same mail in multiple callbacks as if each read consumed it. - Rejected Temporal calls preserve pending direct mail. Calls reaching Temporal execution still advance
InputAuthorityRevision; successful operations clear the direct mailbox. - Serialized capacity
0retains no direct mail only for Graphs without legacy Event declarations. Legacy or mixed Graphs require positive capacity; the Host Inspector minimum stays1. This is separate from Temporal history capacity. - Outbox snapshots
unmanagedpayloads in Enter/Update/Exit and shares the Host outbox limit. Successful commit publishes in State call order; failure/cancellation publishes nothing. Already delivered cross-Actor effects are not undone by Temporal restore.
See State Flow and Event Boundary for the existing Event-to-Intent and Operator Packet paths.
Action progress and independent Conditions
Section titled “Action progress and independent Conditions”Declare [CoCoState("Attack", ProvidesActionProgress = true)] on either an ordinary State or one with Config/Memory. In Update, supply finite, monotonically non-decreasing 0..1 progress through context.TrySetActionProgress(value).
using CoCoFlow.Runtime.Core;
[Condition]public sealed class AttackProgressReadyCondition : CoCoStateCondition, ICoCoStateConditionEvaluator{ public bool Evaluate(CoCoConditionEvaluationContext context) => context.ActionProgress >= 0.8;}The standard provider discovers, registers, and factory-binds this class with empty config. Each [Condition] class must be concrete, non-generic, derive from CoCoStateCondition, implement ICoCoStateConditionEvaluator, and have a public parameterless constructor; an implicit default constructor is sufficient. Multiple classes may share a file. Add the Condition to the desired Graph transition. Its window and Conditions are evaluated only after the active leaf requests an authored outgoing transition, for example with context.TryRequestTransitionTo<TTargetLogic>(). Progress 1 does not request a transition.
The v0.4.5 registration source defines the full declaration requirements.
Shared input and Host setup
Section titled “Shared input and Host setup”- Put
PlayerInputandInputReaderon a persistent object. Configure aMoveaction and the Reader’s Move convenience binding. - Add an
InputIntentto each Host. Assign the same persistent Reader and add the component to the Host’s Intent Sources. - Add
LocomotionOperatorto the Actor (requiresCharacterController), bind it in Operators, and assign the StateGraph Asset.
Standard sources match by payload type; list position is not a type ID. Each gameplay InputSystem update replaces the latest input. InputIntentData holds up to eight records; a later discrete phase replaces an earlier phase for the same action. Reads do not consume input. Hosts can see the same image repeatedly, and short pulses missed while paused are not replayed on resume.
Programmatic callers use non-consuming InputReader.TryReadLatest or sample through InputIntent.TrySample. See Input for the complete boundary.
Operator recovery
Section titled “Operator recovery”Before starting the Host, enable Persistence restore and Temporal restore in Operators as needed. The switches are independent and off by default. Only supported capabilities appear.
| Operator | Save/load recovery | Temporal recovery |
|---|---|---|
LocomotionOperator |
Supported | Supported |
AnimAutoOperator |
Supported | Supported |
CameraOperator |
Supported | Unsupported |
Disabling recovery leaves normal execution and Context capture active. During restore, that Operator’s Outcome keeps its current value, or Layout defaults before the first commit. Graph and Memory restore from the target snapshot, then Derived values rebuild. Settings follow the component when the list is reordered.
For save/load, add PersistenceContext to the Host object and use PersistenceSaveLoadSystem.SaveGame(0) / LoadGame(0). Temporal History capacity 0 disables history; enabled history requires at least 2. History capacity and Operator recovery switches are separate settings. Explicitly bind other resource restore components as needed.
Camera reading and control
Section titled “Camera reading and control”Add CameraIntent and CameraOperator under the controlling Host, bind them in Intent Sources / Operators, and assign the same Director. Assign an explicit CinemachineBrain to the Director. Its Rig Mappings map numeric RigId values to existing Rigs and CameraId values to that Rig’s string Mode IDs.
Reference CoCoFlow.Runtime.Camera.Contracts from StateLogic and declare:
[Intent] public CameraIntentData Camera { get; set; }[Operation] public CameraOperation CameraControl { get; set; }Read the output Camera’s world position through Camera.PositionX/Y/Z and its world Euler rotation in degrees through Camera.RotationX/Y/Z. Inside a State callback, write all five properties for each control request:
CameraControl.RigId = 1001;CameraControl.Active = true;CameraControl.Priority = 60;CameraControl.CameraId = 2003;CameraControl.SchedulingEnabled = true;Configure numeric IDs explicitly on the Director. 0 is valid; list indices and Unity InstanceIDs are unsuitable. Active controls the selected Rig; SchedulingEnabled controls the entire Director.
With CameraOperator’s Persistence restore enabled, the Director captures and restores state through GetState / SetState. Saves use the latest committed Context and restore the existing Rig set (up to 64), without object reconstruction or Lens/FOV data. Restore resets blending. Keep scheduling enabled, or keep camera state unchanged while scheduling is suspended. See Camera.