场景异步加载
IEnumerator LoadSceneSingle(int index)
{
Debug.Log("load");
progress = 0;
yield return new WaitForEndOfFrame();
op = SceneManager.LoadSceneAsync(index);
op.allowSceneActivation = false;
while (op.progress < 0.9f)
{
while (progress < op.progress * 100)
{
progress += 0.1f;
SetProgressText(80 + progress * 0.2f);
yield return new WaitForEndOfFrame();
}
}
while (progress < 100)
{
progress += 0.1f;
SetProgressText(80 + progress * 0.2f);
yield return new WaitForEndOfFrame();
}
op.allowSceneActivation = true;
}
IEnumerator LoadSceneAdditive()
{
progress = 0;
op = SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive);
while (!op.isDone || progress < op.progress * 100)
{
if (progress < 100)
progress += 1f;
SetProgressText(80 + progress * 0.2f);
yield return new WaitForEndOfFrame();
}
while (!op.isDone)
{
yield return new WaitForEndOfFrame();
}
if (op.isDone)
{
Debug.Log("OK");
UICavas.SetActive(false);
}
}
Resources资源异步加载
IEnumerator AsyncLoadResources(List<string> path)
{
for (int i = 0; i < path.Count; i++)
{
yield return LoadResources(path[i], i);
yield return new WaitForEndOfFrame();
}
}
IEnumerator LoadResources(string name, int index)
{
ResourceRequest resourcesRequest = Resources.LoadAsync(name, typeof(GameObject));
progress = 0;
while (!resourcesRequest.isDone)
{
while (progress < resourcesRequest.progress * 100)
{
progress += 1f;
SetProgressText((progress / 100 + index) * (100f / (Path.Count)));
yield return new WaitForEndOfFrame();
}
yield return new WaitForEndOfFrame();
}
resourceRequests.Add(name, resourcesRequest);
if (index >= Path.Count - 1)
{
Debug.Log("OK");
}
}
public GameObject InstantiateObj(string name)
{
if (resourceRequests.ContainsKey(name))
{
GameObject obj = resourceRequests[name].asset as GameObject;
GameObject InstantObj = GameObject.Instantiate<GameObject>(obj);
InstantObj.name = obj.name;
return InstantObj;
}
return null;
}
数据异步处理
using System;
using System.Threading.Tasks;
using UnityEngine;
public class ToolsScript : MonoBehaviour {
//1
async void Start()
{
Debug.Log("开始执行异步方法");
await AsyncMethod(); // 调用异步方法
Debug.Log("异步方法执行完成");
}
async Task AsyncMethod()
{
await Task.Delay(2000); // 模拟一个耗时的操作
Debug.Log("异步方法中耗时的操作完成");
}
//2
public static async void AsyncExecute(Action logic, Action action)
{
await Task.Run(() => logic?.Invoke());
action?.Invoke();
}
}
调用异步方法:
ToolsScript .AsyncExecute(() =>
{
处理数据方法();
}, () =>
{
完成后调用();
});