Unitask笔记

  • 读取文本
//本Class类加载文本
private async void LoadText(){
	文本框.text = ((TextAsset)(await Resources.LoadAsync<TextAsset>("文本文件Resources下不带后缀的地址"))).text;
}

//从其他Class类加载文本
private async void LoadText(){
	其他类名 asyncLoader = new 其他类名();
	文本框.text = ((TextAsset)(await asyncLoader.LoadAsync<TextAsset>("文本文件Resources下不带后缀的地址"))).text;
}

public class 其他类名
{
    /// <summary>
    /// 返回UniTask<Object>类型,这种类型事为Unity定制的,作为替代原生Task<T>的轻量级方案
    /// </summary>
    public async UniTask<Object> LoadAsync<T>(string path) where T : Object
    {
        var asyncOperation = Resources.LoadAsync<T>(path);
        //这个await会将ResourceRequest(class)封装到UniTask的ResourceRequestAwaiter(struct)中
        return await asyncOperation;
    }
}
  • 加载场景
/// <summary>
/// 加载场景过程中显示进度值
/// </summary>
private async void LoadSceneAsync()
{
    //ToUniTask创建一个进度相关的回调
    await SceneManager.LoadSceneAsync("场景地址").ToUniTask(Progress.Create<float>(x =>
    {
        //这里可以修改界面上的进度条
        Debug.Log("进度值:" + x);
    }););
}

-加载图片

public Image Image;

/// <summary>
/// 加载网络图片
/// </summary>
private async void LoadWebPictureAsync()
{
    var webRequest = UnityWebRequestTexture.GetTexture("http://网络图片地址.png");
    var result = await webRequest.SendWebRequest();//发出去请求
    var texture = ((DownloadHandlerTexture)result.downloadHandler).texture;
    Sprite sprite = Sprite.Create(texture, new Rect(Vector2.zero, 
        new Vector2(texture.width, texture.height)), new Vector2(0.5f, 0.5f));
    Image.sprite = sprite;
    Image.SetNativeSize();
}

-Delay等待

public async void DelayTest()
{
    //等待1秒,类似 yield return new WaitForSeconds(1),可以设置 ignoreTimeScale
    await UniTask.Delay(TimeSpan.FromSeconds(1), false);


	//性能最好,可以设置等待时机,PlayerLoopTiming 对应Unity中playerloop的更新时机
    await UniTask.Yield(PlayerLoopTiming.LastUpdate);
    
    //执行在下一帧的update之后,类似 yield return null,和 UniTask.Yield() 效果一样
    await UniTask.NextFrame();
    
    
    //这一帧的最后,类似 yield return new WaitForEndOfFrame(),this是一个MonoBehaviour
    await UniTask.WaitForEndOfFrame(this);
    
    //类似 yield return new WaitForFixedUpdate,和 await UniTask.Yield(PlayerLoopTiming.FixedUpdate)效果一样
    await UniTask.WaitForFixedUpdate();

    //延迟5帧
    await UniTask.DelayFrame(5);

    //类似 yield return new WaitUntil(() => count > 10),当count > 10时才执行后面逻辑
    await UniTask.WaitUntil(() => count > 10);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值