U3D Loadin场景

    xiaoxiao2023-09-28  193

    通常游戏的主场景包含的资源较多,这会导致加载场景的时间较长。为了避免这个问题,可以首先加载Loading场景,然后再通过Loading场景来加载主场景。因为Loading场景包含的资源较少,所以加载速度快。在加载主场景的时候一般会在Loading界面中显示一个进度条来告知玩家当前加载的进度。在Unity中可以通过调用Application.LoadLevelAsync函数来异步加载游戏场景,通过查询AsyncOperation.progress的值来得到场景加载的进度。 我们首先将AsyncOperation.allowSceneActivation设为false,当加载完成后再设为true。代码看上去没有错,但是执行的结果是进度条最后会一直停留在90%上,场景不会切换。通过打印log发现AsyncOperation.isDone一直为false,AsyncOperation.progress的值增加到0.9后就保持不变了,也就是说场景永远不会被加载完毕。

    在这个帖子中找到了答案,原来把allowSceneActivation设置为false后,Unity就只会加载场景到90%,剩下的10%要等到allowSceneActivation设置为true后才加载,这不得不说是一个坑。所以代码改为如下。当AsyncOperation.progress到达0.9后,就直接把进度条的数值更新为100%,然后设置AsyncOperation.allowSceneActivation为ture,让Unity继续加载未完成的场景。

    public Slider slider;

    public Text text; // Start is called before the first frame update void Start() { LoadGame(); } // Update is called once per frame void Update() { } public void LoadGame() { StartCoroutine(LoadGameing(1)); } private IEnumerator LoadGameing(int scenes) { int displayProgress = 0; int toProgress = 0; AsyncOperation op = Application.LoadLevelAsync(scenes);//异步加载 op.allowSceneActivation = false;//禁止Unity加载完毕后自动切换场景,**加粗样式** while (op.progress<0.9f) { toProgress = (int) op.progress * 100; while (displayProgress < toProgress) { ++displayProgress; SetLoadingPercentage(displayProgress); yield return new WaitForEndOfFrame(); } } toProgress = 100; while (displayProgress < toProgress) { ++displayProgress; SetLoadingPercentage(displayProgress); yield return new WaitForEndOfFrame(); } op.allowSceneActivation = true; } public void SetLoadingPercentage(int i) { slider.value = i * 0.01f; text.text = i.ToString() + "%"; }
    最新回复(0)