异步加载卡顿问题解决

来源:互联网 发布:合肥宽信网络运营中心 编辑:程序博客网 时间:2024/06/11 17:50

关于异步加载,很多人都是卡住,然后就进场景了,中间进度条基本没作用了。

雨松大神讲过一篇异步加载的,但是同样也是有问题的,跟直接跳转没什么区别。

但事实上,只要加上一句话就可以完成了。

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. yield return new WaitForEndOfFrame();  
等待直到所有的摄像机和GUI被渲染完成后,在该帧显示在屏幕之前。


代码如下:

[csharp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. using UnityEngine;    
  2. using System.Collections;    
  3.     
  4. public class Loading : MonoBehaviour {    
  5.     
  6.     private float fps = 10.0f;    
  7.     private float time;    
  8.     //一组动画的贴图,在编辑器中赋值。    
  9.     public Texture2D[] animations;    
  10.     private int nowFram;    
  11.     //异步对象    
  12.     AsyncOperation async;    
  13.     
  14.     //读取场景的进度,它的取值范围在0 - 1 之间。    
  15.     int progress = 0;    
  16.     
  17.     void Start()    
  18.     {    
  19.         //在这里开启一个异步任务,    
  20.         //进入loadScene方法。    
  21.         StartCoroutine(loadScene());    
  22.     }    
  23.     
  24.     //注意这里返回值一定是 IEnumerator    
  25.     IEnumerator loadScene()    
  26.     {    
  27.         yield return new WaitForEndOfFrame();//加上这么一句就可以先显示加载画面然后再进行加载  
  28.         async = Application.LoadLevelAsync(Globe.loadName);    
  29.     
  30.         //读取完毕后返回, 系统会自动进入C场景    
  31.         yield return async;    
  32.     
  33.     }    
  34.     
  35.     void OnGUI()    
  36.     {    
  37.         //因为在异步读取场景,    
  38.         //所以这里我们可以刷新UI    
  39.         DrawAnimation(animations);    
  40.     
  41.     }    
  42.     
  43.     void Update()    
  44.     {    
  45.     
  46.         //在这里计算读取的进度,    
  47.         //progress 的取值范围在0.1 - 1之间, 但是它不会等于1    
  48.         //也就是说progress可能是0.9的时候就直接进入新场景了    
  49.         //所以在写进度条的时候需要注意一下。    
  50.         //为了计算百分比 所以直接乘以100即可    
  51.         progress =  (int)(async.progress *100);    
  52.     
  53.         //有了读取进度的数值,大家可以自行制作进度条啦。    
  54.         Debug.Log("xuanyusong" +progress);    
  55.     
  56.     }    
  57.     //这是一个简单绘制2D动画的方法,没什么好说的。    
  58.     void   DrawAnimation(Texture2D[] tex)    
  59.     {    
  60.     
  61.         time += Time.deltaTime;    
  62.     
  63.          if(time >= 1.0 / fps){    
  64.     
  65.              nowFram++;    
  66.     
  67.              time = 0;    
  68.     
  69.              if(nowFram >= tex.Length)    
  70.              {    
  71.                 nowFram = 0;    
  72.              }    
  73.         }    
  74.         GUI.DrawTexture(new Rect( 100,100,40,60) ,tex[nowFram] );    
  75.     
  76.         //在这里显示读取的进度。    
  77.         GUI.Label(new Rect( 100,180,300,60), "lOADING!!!!!" + progress);    
  78.     
  79.     }    
  80.     
  81. }    
0 0