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

[置顶] unity中关于异步loading场景的加载

2016-06-07 16:20 609 查看
当我们在加载一个场景时,如果场景的资源比较小的话是很快就跳入下一个场景的,如果场景资源多的话加载就会很慢,这时如果让用户一直等待会造成用户的体验很差,所以我们采用异步加载。

这里我使用的是UGUI做的,当然用NGUI也可以,只是换一下组件而已。

using UnityEngine;

using System.Collections;

using UnityEngine.UI;

public class ExcessiveMenuPanel : MonoBehaviour {

    public Scrollbar loadScrollbar;//场景中的进度条

    public Text loadText;//显示进度的文本

    // Use this for initialization

    void Start () {

        //这里传在buildSetting中的id,或者传字符串,把下面的int改为string

        StartCoroutine(StartLoading_4(2));

    }

    /// <summary>

    /// 加载场景,只能加载在BuildSettings设置的场景,我在做加载AssetBundle加载场景是不行的

    /// </summary>

    /// <param name="scene"></param>

    /// <returns></returns>

    private IEnumerator StartLoading_4(int scene)

    {

        int displayProgress = 0;

        int toProgress = 0;

        AsyncOperation op = Application.LoadLevelAsync(scene);

        op.allowSceneActivation = false;

        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;

    }

    /// <summary>

    /// 设置进度条和文本

    /// </summary>

    /// <param name="num"></param>

    private void SetLoadingPercentage(float num)

    {

        loadScrollbar.size = num * 0.01f;

        loadText.text = num.ToString() + "%";

    }

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