Description
The EnabledToken
property of a GameObject
provides a CancellationToken
that is automatically cancelled when the GameObject
is either disabled or destroyed. This can be useful for managing asynchronous operations that should be terminated when the GameObject
is no longer active or valid.
Usage
Use the EnabledToken
to monitor the lifecycle of a GameObject
and cancel tasks or operations when the GameObject
is disabled or destroyed. This is particularly useful in scenarios where you have long-running tasks or operations that should not continue if the GameObject
is no longer available.
Example
// Example of using EnabledToken to cancel an asynchronous operation
public async Task PerformOperationAsync(GameObject gameObject)
{
try
{
// Pass the EnabledToken to the asynchronous operation
await SomeLongRunningOperationAsync(gameObject.EnabledToken);
}
catch (OperationCanceledException)
{
// Handle the cancellation
Console.WriteLine("Operation was cancelled because the GameObject was disabled or destroyed.");
}
}
private async Task SomeLongRunningOperationAsync(CancellationToken cancellationToken)
{
// Simulate a long-running operation
await Task.Delay(5000, cancellationToken);
}