menu_bookDocumentation

Async Tasks and Coroutines in s&box Components

calendar_today May 20, 2026 schedule ~1 min read person PatrickJr verified 50

Async tasks in s&box run on the main thread by default, operating like coroutines. They are the recommended replacement for coroutines.

Basic Async Method

CSHARP
async Task PrintSomething( float waitSeconds, string message )
{
    await Task.DelaySeconds( waitSeconds );
    Log.Info( message );
}

Frame-by-Frame Animation

Use Task.Frame() to wait one frame, enabling smooth interpolation:

CSHARP
async Task LerpSize( float seconds, Vector3 to, Easing.Function easer )
{
    TimeSince timeSince = 0;
    Vector3 from = WorldScale;

    while ( timeSince < seconds )
    {
        WorldScale = Vector3.Lerp( from, to, easer( timeSince / seconds ) );
        await Task.Frame();
    }
}

await LerpSize( 3.0f, Vector3.One * 3.3f, Easing.BounceOut );
await LerpSize( 1.0f, Vector3.One * 4.0f, Easing.EaseInOut );

Running Multiple Tasks in Parallel

CSHARP
async Task DoMultipleThings()
{
    Task taskOne = PrintSomething( 2.0f, "One" );
    Task taskTwo = PrintSomething( 3.0f, "Two" );
    await Task.WhenAll( taskOne, taskTwo );
}

Calling Async from Synchronous Code

CSHARP
protected override void OnEnabled()
{
    _ = DoMultipleThings(); // fire and forget

    // Or with a callback:
    GetKanyeQuote().ContinueWith( task => Log.Info( task.Result ) );
}

Lifecycle Safety

Async methods are NOT guaranteed to stop when a GameObject or Component is destroyed. However, when awaiting via Component.Task, the task is automatically cancelled if the GameObject becomes invalid.

Always consider: what happens if the object is destroyed mid-await? Use CancellationToken for cancellable operations, and guard against stacking tasks (e.g., user pressing a button multiple times during a delay).

Was this helpful?