CancellationToken EnabledToken { get; set; }

robot_2Generated
code_blocksInput

Description

The EnabledToken property of a GameObject provides a CancellationToken that is cancelled when the GameObject is either disabled or ceases to exist. This can be useful for managing asynchronous operations that should be terminated when the GameObject is no longer active or present in the scene.

Usage

Use the EnabledToken to monitor the lifecycle of a GameObject and cancel any ongoing tasks or operations when the GameObject is disabled or destroyed. This helps in preventing memory leaks and ensuring that operations do not continue on non-existent objects.

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 SomeAsyncOperation(gameObject.EnabledToken);
    }
    catch (OperationCanceledException)
    {
        // Handle the cancellation
        Console.WriteLine("Operation was cancelled because the GameObject was disabled or destroyed.");
    }
}

private async Task SomeAsyncOperation(CancellationToken cancellationToken)
{
    // Simulate a long-running operation
    await Task.Delay(5000, cancellationToken);
}