Unity3D学习笔记之异步加载卡顿问题解决办法

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

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

0个评论