Hi there,
I’m migrating my Coroutines to UniTaskVoid.
While I’m doing that I’ve just stucked with 3 things:
1. Is it true to cancel a Task on demand like StopCounter() method below?
2. Is it true to call cancellationToken: _cancellationToken.token both on
await UniTask.WaitUntil(() => isReady, cancellationToken: _cancellationToken.Token);
await UniTask.Delay(TimeSpan.FromSeconds(1), cancellationToken: _cancellationToken.Token);
3. How to cancel Task on destroy?
Because when I load another scene I can see the task still running on UniTask Tracker.
Here is my codes:
public class CounterController : MonoBehaviour
{
public bool isReady;
public int number;
private CancellationTokenSource _cancellationToken;
public void StartCounter()
{
if (_cancellationToken != null && !_cancellationToken.IsCancellationRequested)
_cancellationToken.Cancel();
Counter().Forget();
}
public void StopCounter()
{
if (_cancellationToken != null && !_cancellationToken.IsCancellationRequested)
_cancellationToken.Cancel();
}
private async UniTaskVoid Counter()
{
_cancellationToken = new CancellationTokenSource();
await UniTask.WaitUntil(() => isReady, cancellationToken: _cancellationToken.Token);
while (true)
{
number++;
await UniTask.Delay(TimeSpan.FromSeconds(1), cancellationToken: _cancellationToken.Token);
}
}
}
Thanks in advance to everyone who took the time.