赞
踩
背景:之前用Unity2020 + UniTask开发的项目,结果用户的需求是要集成到Unity2017.4.37的一个工程文件里面,所有只能返祖了。
/// <summary>
/// 方法:WaitUntil
/// </summary>
/// <param name="predicate">条件语句</param>
/// <param name="sleep">delay事件</param>
/// <returns>Task</returns>
public static async Task WaitUntil(Func<bool> predicate, int sleep = 50)
{
while (!predicate())
{
await Task.Delay(sleep);
}
}
/// <summary>
/// 方法:等待X帧
/// </summary>
/// <returns>Task</returns>
public static async Task DelayFrame(int count)
{
var current = Time.frameCount;
while (Time.frameCount - current > count)
{
await Task.Yield();
}
}
/// <summary> /// 为Button定制一个扩展方法:点击事件的异步等待 /// </summary> /// <param name="button">按钮Button</param> /// <param name="delayMs">循环等待中delay的时间-毫秒</param> /// <returns>Task</returns> public static async Task OnClickAsync(this Button button,int delayMs = 50) { bool clicked = false; UnityAction ClickAction = () => { clicked = true; //Debug.Log($"ClickAction() was called {Time.realtimeSinceStartup}"); }; //Debug.Log("添加侦听"); button.onClick.AddListener(ClickAction); //此处不能用兰姆达,不然传入的是临时定义的方法,而不是提前定义的。 while (!clicked) { await Task.Delay(delayMs); //等待时间【ms毫秒】 } //Debug.Log("移除侦听"); button.onClick.RemoveListener(ClickAction); ClickAction = null; }
代码【1】——扩展Task
using System; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; /// <summary> /// Task扩展工具 【System.Threading.Tasks 】 /// not UniTask 【Cysharp.Threading.Tasks】 /// </summary> public static class TaskUtils { /// <summary> /// 方法:WaitUntil /// </summary> /// <param name="predicate">条件语句</param> /// <param name="sleep">delay事件</param> /// <returns>Task</returns> public static async Task WaitUntil(Func<bool> predicate, int sleep = 50) { while (!predicate()) { await Task.Delay(sleep); } } /// <summary> /// 方法:等待X帧 /// </summary> /// <returns>Task</returns> public static async Task WaitFrame(int count) { var current = Time.frameCount; while (Time.frameCount - current > count) { await Task.Yield(); } } /// <summary> /// 方法:等待X帧 /// </summary> /// <returns>Task</returns> public static async Task DelayFrame(int count) { var current = Time.frameCount; while (Time.frameCount - current > count) { await Task.Yield(); } } }
【2】——测试Task
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Threading.Tasks; using System; /// <summary> /// 按钮被点击的事件绑定 /// </summary> public class ButtonClicked : MonoBehaviour { public Button myButton; // Use this for initialization void Start () { Func<Task> Flow = async() => { while (true) { Debug.Log($"等待按钮被点击-{Time.realtimeSinceStartup}"); await myButton.OnClickAsync(); Debug.Log($"按钮点击完成-{Time.realtimeSinceStartup}"); } }; Flow(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。