- 读取文本
//本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);
}