Unity 异步加载场景

版本:unity 5.3.4  语言:C#

 

老大让我做什么来着?好像就是测试代码、录个视频吧,有点忘了,应该不是什么重要的事情,反正我还是研究我的代码。

 

现在就看看工程的代码,正好看到了一段异步加载场景,它里面写的太乱了,我整理了一下发上来。

 

这边用到了UGUI的Slider组件,玩家自行添加一下。

 

代码如下(GameSystem是一个单例、一个全局类):

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class LoadingScene : MonoBehaviour {

    public Slider slider;

    AsyncOperation async;
    int process = 0;    //进度,一帧最多加1,到100时进入新的场景

    // Use this for initialization
    void Start()
    {
        StartCoroutine("Loading");  //开一个协程
    }
	
	IEnumerator Loading()
    {
        Debug.Log("Start to Load");

        // 异步加载场景
        async = Application.LoadLevelAsync(GameSystem.getInstance().loadingScene);
        async.allowSceneActivation = false;

        // 没有加载完的情况下一直在这边循环
        while (!async.isDone)
        {
            //if (async.progress >= 0.9f)  //似乎是unity的一个bug,只能加载到90%(注意这边0.9f别写成0.9,这是一个精度的问题,double型的0.9是永远达不到的)
            //    break;
            if (process >= 100)
                break;
            yield return null;
        }

        Debug.Log("Load Complete");
        yield return new WaitForSeconds(0.5f);

        // 进入场景
        async.allowSceneActivation = true;
    }

    void OnGUI()
    {
        if (async == null)
            return;

        // 进度条的显示
        if (async.progress / 0.9f * 100 > process)
            ++process;
        slider.value = process / 100f;


        GUILayout.Label(process.ToString());
        Debug.Log("Loading " + process);
    }
}

以上。


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值