异步加载场景

来源:互联网 发布:推荐算法 gbdt 编辑:程序博客网 时间:2024/06/08 14:55

建立两个场景,场景2中有很多gameobject,场景1中是测试代码,点击跳转按钮,显示加载进度,加载完成后跳转场景。

可以把跳转单独做成一个loading场景,跳转场景时传递要跳转的场景给loading,loading作为游戏中专门用来衔接的场景。

如下图所示:

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;//需要添加这个命名空间

public class AsyncTest : MonoBehaviour {
    private AsyncOperation m_async;
    private int nowProcess; 
    // Use this for initialization
    void Start () {
        UIEventListener.Get(transform.Find("jump").gameObject).onClick = delegate(GameObject go) {
            StartCoroutine(LoadScene());//点击按钮开始加载场景
        };
    }
    
    // Update is called once per frame
    void Update () {
        if (m_async == null) {
            return;
        }
        int toProcess;  
        // async.progress 你正在读取的场景的进度值  0---0.9    
        // 如果当前的进度小于0.9,说明它还没有加载完成,就说明进度条还需要移动    
        // 如果,场景的数据加载完毕,async.progress 的值就会等于0.9  
        if(m_async.progress < 0.9f)  
        {  
            toProcess = (int)m_async.progress * 100;  
        }else  
        {  
            toProcess = 100;  
        }  
       
        if(nowProcess < toProcess)  
        {  
            nowProcess++;  
        }  
        string result = (nowProcess / 100f).ToString ("0.00");//保留两位小数
        transform.Find("Label").GetComponent<UILabel>().text = result;//实时显示加载结果

        // 设置为true的时候,如果场景数据加载完毕,就可以自动跳转场景   
        if(nowProcess == 100)  
        {  
            m_async.allowSceneActivation = true;  
        }  
    }

    private IEnumerator LoadScene()
    {
        m_async = SceneManager.LoadSceneAsync("jump2");//JUMP2不区分大小写
        m_async.allowSceneActivation = false;//不允许跳转
        yield return m_async;
    }
}


demo百度云地址:
链接:http://pan.baidu.com/s/1c2d5MIs 密码:ozu7


0 0