您的位置:首页 > 移动开发 > Unity3D

Unity——Loading界面-异步加载场景

2021-11-01 17:25 1556 查看

Loading界面-异步加载场景

Demo展示

加载新场景时,需要加载大量模型外部文件等,比较耗时,又不能让画面卡住不动;

很多时候会做一个加载界面显示读条;

代码

非常简直,就不赘述了;

一个slider条,progress为异步百分比;

限制读条3s结束,小于3s等待;

注意异步读条progress到不了1,所以0.9判断加载完成;

public class Loading : MonoBehaviour
{
public string scenceName;

AsyncOperation async;

public Slider m_pProgress;

private int progress = 0;

private float time = 3f;
private float startTime = 0;
private void Start()
{
StartCoroutine(LoadScenes());
startTime = Time.time;
}

IEnumerator LoadScenes()
{
int nDisPlayProgress = 0;
async = SceneManager.LoadSceneAsync(scenceName);
async.allowSceneActivation = false;
while (async.progress < 0.9f)
{
progress = (int)async.progress * 100;
while (nDisPlayProgress < progress)
{
++nDisPlayProgress;
m_pProgress.value = (float)nDisPlayProgress / 100;
yield return new WaitForEndOfFrame();
}

yield return null;
}

progress = 100;
while (nDisPlayProgress < progress)
{
++nDisPlayProgress;
m_pProgress.value = (float)nDisPlayProgress / 100;
yield return new WaitForEndOfFrame();
}

float temp = Time.time - startTime;
if (temp < time)
yield return new WaitForSeconds(time - temp);

async.allowSceneActivation = true;
}
}

测试代码:

加载场景时,记在loading界面,设置需要加载的场景名称;

public class MainScence : MonoBehaviour
{
public Button btnLoad;
void Start()
{
btnLoad.onClick.AddListener(OnLoadFight);
}

private void OnLoadFight()
{
GameObject go = Instantiate(Resources.Load<GameObject>("Loading"), transform);
go.GetComponent<Loading>().scenceName = "FightScence";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: