Skip to content

Components and events ​

Use a PartComponent for behaviour that belongs to each placed instance of a part. Use mod.Events to observe game actions, such as world loading and part placement.

Add a saved timer ​

Add this class to the first-mod project. It accumulates simulation time on authority.

csharp
using StellarWorks.Parts;

namespace MyFirstMod
{
    public sealed class ElapsedTimer : PartComponent
    {
        [Persist("elapsed"), Replicate("elapsed")]
        public float ElapsedSeconds { get; private set; }

        public override void OnServerTick(float deltaTime)
        {
            ElapsedSeconds += deltaTime;
            MarkStateDirty();
        }
    }
}

Register the factory once in OnInitializeMelon and attach it before part.Register().

csharp
var timer = mod.Components.Register("timer", _ => new ElapsedTimer(), new ComponentOptions
{
    Role = ComponentRole.Authority,
    Tick = true
});
part.AddComponent(timer);

Each placed instance gets its own timer. Persist saves the property with the world. Replicate exposes it to a client visual component, which can read Part.Replicated<float>(timer, "elapsed") and react in OnReplicatedStateChanged. For frequently changing fields, mark state dirty at the cadence the display needs. Persistent fields are captured at save time.

Use an authority component to change simulation state. Use a visual component for Unity display and cleanup. Handle both OnPlaced and OnLoaded when building initial state that depends on a part's active context. Release per-instance subscriptions and visuals in OnRemoved. Lifecycle and component reference

Observe gameplay events ​

Subscribe from OnInitializeMelon using a unique name in your mod. This logs world loads on the game thread.

csharp
mod.Events.World.Loaded.Subscribe("report_world", evt =>
    mod.Logger.Info($"Loaded {evt.World.Id} as {evt.World.Role}."));

Subscriptions default to the framework lifetime. Dispose the returned handle on the game thread to stop receiving events. For listeners installed for a single session, use new SubscriptionOptions(Lifetime: RegistrationLifetime.World) while that session is open. Use SessionRole.Authority when a handler changes shared gameplay or opens world storage.

For validation before the native build applies changes, subscribe to mod.Events.Parts.BeforePlacement and call request.Cancel(reason) within the callback. Keep placement checks synchronous and read-only apart from the cancellation.

StellarWorks documentation · Mods for StellarDrive