Skip to content

Runtime callbacks and state ​

Use callbacks for behaviour and declared fields for state that saves or replicates. The server writes state; clients read replicated values.

Add a saved timer ​

Add using Newtonsoft.Json.Linq;. Put these properties inside the tutorial controller's PartDefinition:

csharp
State = new PartStateDefinition
{
    Version = 1,
    Fields = new[]
    {
        new PartStateField { Name = "elapsed", Default = new JValue(0d) }
    }
},
Callbacks = new PartCallbacks
{
    ServerTick = (part, deltaTime) =>
    {
        double elapsed = part.State.Get<double>("elapsed");
        part.State.Set("elapsed", elapsed + deltaTime);
    }
}

The timer saves and replicates because both field flags default to true. Showcase adds a client display.

Callback timing ​

CallbackPurpose
SpawnedInitialise instance bookkeeping
ServerTickRun server simulation
ClientUpdateUpdate loaded client visuals
NativeStateChangedObserve the donor's native state changes
StateChangedReact to custom field changes
RemovedRelease bookkeeping; final state is still readable

All run on the main thread. A host has separate server/client instances. Only live server instances can write. A callback exception disables that callback for the affected instance and is logged.

Fields and updates ​

Defaults define each field's JSON type. Use 0d for floating values and 0L for integers. Set Saved=false for transient fields, or Replicated=false for server-private fields.

Get<T> and Snapshot() return copies. Commit edits with Set; use Set(JObject) to update multiple fields atomically. Use Validate to reject invalid state.

Changing saved fields ​

Increment Version and provide Migrate when changing the saved schema. Return current saved fields only; omitted fields receive defaults. Keep matching schemas on all peers.

See the runtime API reference for signatures, limits, and migration rules, or Showcase's state example.

StellarStriderLib documentation · Mods for StellarDrive