Table of Contents

Script System Extensions

Extension methods for ScriptSystem, in the Stride.CommunityToolkit.Engine namespace. They cover two jobs: awaiting time inside an async script, and scheduling work as a micro thread without writing one yourself.

Waiting

Delay() and ExecuteInTime() each have a warped twin. Warped time is scaled by the game's update time factor, so a warped wait slows down when the game does; the plain version does not. Neither counts while the game is paused, and both end early when the game stops.

  • Delay() - Waits the given number of seconds of game time, ignoring the update time factor.
  • DelayWarped() - Waits the given number of seconds in warped time, so slow motion stretches the wait.
  • WaitFor() - The same as Delay() but takes a TimeSpan. Awaiting it throws ArgumentOutOfRangeException if the delay is zero or negative.

Running something every frame for a while

Scheduling micro threads

The Add* methods return the MicroThread they created, so you can keep it and cancel it later, and each takes an optional priority. A delay, interval or duration of zero or less throws ArgumentOutOfRangeException.

  • AddAction() - Runs an action once, after a delay. A second overload adds a repeatEvery interval and keeps running it.
  • AddTask() - The async counterpart of AddAction(), taking a Func<Task>. Also has a repeating overload.
  • AddOverTimeAction() - Runs an action every frame for a duration, passing progress from 0.0f to 1.0f. This is the one to reach for when tweening something.
  • AddOnEventAction() - Runs an action every time an event is published. Takes an EventKey<T> or an existing EventReceiver<T>.
  • AddOnEventTask() - The async counterpart of AddOnEventAction().
  • CancelAll() - Cancels every micro thread in a collection and clears it. An extension on the collection, not on the script system.

Reaching the game thread

Scenes, entities and components may only be touched from the game thread. A network callback, a timer or a task that finished on the thread pool hands its work over with these; the work runs on the next update.

  • RunOnGameThread() - Queues an action for the game thread, from any thread. Build the entity where you are, add it to the scene inside the action.
  • RunOnGameThreadAsync<T>() - The same for a function whose result you need back, as a Task<T> to await on the calling thread.
// On a thread-pool thread, once a download has finished
game.Script.RunOnGameThread(() => CreateCrate(bytes).Scene = scene);

var count = await game.Script.RunOnGameThreadAsync(() => scene.Entities.Count);
Tip

When the action passed to an Add* method is an instance method of a ScriptComponent, the micro thread stops on its own once that component or its entity is removed. Pass a lambda that closes over other state and you own the lifetime yourself - keep the MicroThread and cancel it. RunOnGameThread always wraps the action, so its action runs even if its script was removed.

See also