异步编程学习
UniTask
UniTask
访问UniTask的GitHub的主页可以直接下载unity Package进行导入,或者通过 Package Manager导入,导入完成之后根据文档加一下 宏定义“UNITASK_DOTWEEN_SUPPORT”
这样就可以正常的控制DoTween了
2.UniTask 的简单使用
// UniTask 是可以作用到DoTween上的
using Cysharp.Threading.Tasks;
using DG.Tweening;
using System;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class UnitaskCancel : MonoBehaviour
{
//当我们点击取消按钮的时候 会发送一个取消指令,接收到指令的UniTask都会取消
// CacellationTokenSource 是原生的类
private CancellationTokenSource cts = new CancellationTokenSource();
[SerializeField] private Button cancelButton;
[SerializeField] private Transform cube;
private UniTask[] cancelTaskArray;
private void Awake()
{
cancelButton.onClick.AddListener(cancel);
InitUniTask();
}
private async void InitUniTask() {
UniTask one = cube.DOMove(new Vector3(5, 0, 5), 2f).SetEase(Ease.InOutQuart).ToUniTask(cancellationToken:cts.Token);
UniTask two = cube.DOScale(new Vector3(2, 2, 2), 5f).SetEase(Ease.InOutQuart).ToUniTask(cancellationToken: cts.Token);
UniTask three = cube.DORotate(new Vector3(90, 90, 90), 2f).SetEase(Ease.InOutQuart).OnComplete(()=>{
Debug.Log("CompleteDORotate");
}).ToUniTask(cancellationToken: cts.Token);
cancelTaskArray = new UniTask []{ one, two,three };
// 等待全部的任务完成才会继续执行
// 注意这里的任务 是一起开始的,如果想要一个一个完成 需要直接await 具体的Unitask
var waitAll = UniTask.WhenAll(cancelTaskArray);
//await UniTask.Delay(TimeSpan.FromSeconds(1f)) ;
await waitAll;
Debug.Log("Complete");
}
private void InitDotween() {
cube.DOScale(new Vector3(2, 2, 2), 5f).SetEase(Ease.InOutQuart);
cube.DORotate(new Vector3(90, 90, 90), 2f).SetEase(Ease.InOutQuart);
cube.DOMove(new Vector3(5, 0, 5), 2f).SetEase(Ease.InOutQuart);
}
private void cancel() {
cts.Cancel();
}
}
下一篇 将会使用UniTask完成一个小案例