Type Alias ComponentCoroutine<T>

ComponentCoroutine<T>: ((this: Component, ...args: any) => Generator<any>)

The ComponentCoroutine type represents a coroutine that is executed on a Component.

Coroutines are helper functions that can be used to create complex behavior that is executed over multiple frames. A coroutine can yield to pause execution and return control to the calling coroutine. The coroutine will resume execution in the next frame.

To create a coroutine, create a function that returns a generator and activate it on a Component using a call to Component.startCoroutine or Component.startFixedCoroutine.

Coroutine stop automatically if they reach the end of the function or a return statement. To stop a coroutine simply call Component.stopCoroutine or Component.stopAllCoroutines.

The following example shows how to create a component that schedules two coroutines:


export class MyComponent extends Component
{
protected override onEnable(): void
{
// start the coroutine that updates each frame
this.startCoroutine(this.onMyCourtine);

// start the coroutine that updates each fixed frame, together with the physics updates
this.startFixedCoroutine(this.onMyFixedCourtineWithArguments, 3, "MyMessage");
}

//
// A coroutine with arguments that will be called on each fixed update of the component.
// It will wait for the specified duration and then log a message
// and terminate the execution of `onMyCourtine`.
//
protected *onMyFixedCourtineWithArguments(durationInSeconds: number, text: string)
{
Debug.log("Starting coroutine with arguments=" + JSON.stringify(arguments));
yield waitForSeconds(durationInSeconds);
Debug.log("Finished coroutine with arguments!");

this.stopCoroutine(this.onMyCourtine);
}

//
// A coroutine that will be called on each update of the component.
// It will wait for one second and then log a message.
// This coroutine will run forever, until terminated.
//
protected *onMyCourtine()
{
Debug.log("Starting coroutine");
while(true)
{
waitForSeconds(1);
Debug.log("Coroutine was updated!");

}
}
}

Type Parameters

  • T extends ((this: Component, ...args: any) => Generator<any>)