本例注意的地方:
- 异步方法有返回值,为UniTaskVoid
- 委托应该用Func,因为有返回值
- 两种实现方法:
? ? ? ? ?委托+普通方法+后续初始化绑定
? ? ? ? ?委托+匿名方法+直接初始化绑定
用到的包:UniTask
![](https://img-blog.csdnimg.cn/ba2cf3ef64c147668a52a2c0a2e5f117.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAZHpqMjAyMQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
?
ing System.Collections; using System.Collections.Generic; using UnityEngine; using Cysharp.Threading.Tasks; using System;
public class UnitaskTest : MonoBehaviour { ? ? public static Func<UniTaskVoid> MyFunc;
? ? private async UniTaskVoid MyAction() ? ? { ? ? ? ? Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}"); ? ? ? ? await UniTask.Delay(TimeSpan.FromSeconds(1.0)); ? ? ? ? Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}"); ? ? }
? ? private void Awake() ? ? { ? ? ? ? MyFunc = MyAction; ? ? }
? ? // Start is called before the first frame update ? ? void Start() ? ? { ? ? ? ?? ? ? }
? ? // Update is called once per frame ? ? void Update() ? ? { ? ? ? ? if (Input.GetKeyDown(KeyCode.Space)) ? ? ? ? { ? ? ? ? ? ? MyFunc(); ? ? ? ? } ? ? } }
一种更简洁的写法:委托 = 匿名方法,注意关键字【async】的位置
public static Func<UniTaskVoid> MyFunc = async () =>
{
Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}");
await UniTask.Delay(TimeSpan.FromSeconds(1.0));
Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}");
};
全部代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System;
public class UnitaskTest : MonoBehaviour
{
public static Func<UniTaskVoid> MyFunc = async () =>
{
Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}");
await UniTask.Delay(TimeSpan.FromSeconds(1.0));
Debug.Log($"++++++++++++++++++++++++++执行时间:{Time.realtimeSinceStartup}");
};
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
MyFunc();
}
}
}
以上代码测试通过:vs2019 + Unity2020.3
|