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

Unity场景加载与进度条

2017-05-22 21:46 656 查看
因为项目的一个场景比较大,在加载的时候有明显的等待,所以决定做个进度条。

讲道理做了多媒体之后已经很久没有在一个项目里用到多个场景了,上一次用的时候还是application.loadlevel,现在已经改成了SceneManager。

直接加载场景

1.using UnityEngine.SceneManagement;

2.SceneManager.LoadScene(index/scenename)

做场景加载要确保场景已经被添加进了build setting的scenes in build中

加个进度条

首先将SceneManager.LoadScene换成SceneManager.LoadSceneAsync,它返回一个AsyncOperation类型的返回值,这个返回值包括了progress,isdone属性,还可以设置是否场景加载完就跳转(有的游戏是场景加载完需要按一个按钮才进入场景,有的是直接进入)

然后需要根据AsyncOperation的progress修改ui的值,实现进度条

进度条在其实就是讲一张图片的image type设置为filled,然后选择水平,然后修改它的fill amount







我看到网上有一篇博客介绍了如何让进度条更平滑,感觉还不错,只是贴代码的时候估计没有测试,数据类型转换都不对,导致一直死循环。

代码如下

IEnumerator startLoad(string sceneName)
{
int displayProgress = 0;
int targetProgress = 0;
AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single);
ao.allowSceneActivation = false;

while (ao.progress < 0.9f)
{
Debug.Log(ao.progress);

targetProgress = (int)(ao.progress * 100);
while (displayProgress < targetProgress)
{
displayProgress++;
//Debug.Log(displayProgress);
percentText.text = displayProgress + "%";
loadBar.fillAmount = (float)displayProgress / 100;
yield return new WaitForEndOfFrame();
}

//yield return new WaitForEndOfFrame();
}
//Debug.Log(targetProgress);
targetProgress = 100;
while (displayProgress < targetProgress)
{
displayProgress++;
//Debug.Log(displayProgress);
percentText.text = displayProgress + "%";
loadBar.fillAmount = (float)displayProgress / 100;

yield return new WaitForEndOfFrame();
}

ao.allowSceneActivation = true;
}


补充,我使用几个cube测试场景跳转的时候发现光线变黑了,这个问题很久前就听别人说过但因为自己一直用不上场景跳转没有就没注意,今天顺势百度了一下

选择菜单window-》lighting 取消auto generate,点击generate lighting。不明觉厉

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: