一、异步加载场景代码(安卓)
安卓:异步加载场景代码和优化进度条
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //引入命名空间
using UnityEngine.SceneManagement;//引入命名空间
public class S2Manager : MonoBehaviour
{
public Animation anim;
public Button button;
//UI进度条
public Slider _proSlider; //滑动条
//目的是对场景进行控制 获取进度值 和允许显示
private AsyncOperation _async;
//UI应该达到的进度
private int _currProgress;
//1. 获取滑动条
//协同加载(异步加载 不断获取进度值 经过计算赋值给滑动条)
// Use this for initialization
void Start()
{
_currProgress = 0;
_async = null;
}
public void Load()
{
StartCoroutine(LoadScene());
}
// Update is called once per frame
void Update()
{
//目的就是现实进度
//_proSlider.value = _currProgress / 100.0f;
}
IEnumerator LoadScene()
{
anim.Play();
yield return new WaitForSeconds(1);
_proSlider.gameObject.SetActive(true);
Debug.Log("开始加载场景");
//异步加载
_async = SceneManager.LoadSceneAsync("Main"); //跳转场景为S3
_async.allowSceneActivation = false;
while (_async.progress<0.9F)
{
_proSlider.value += 0.002F;
yield return new WaitForFixedUpdate();
}
Debug.Log("场景准备完场");
while (_proSlider.value < 1)
{
_proSlider.value += 0.002F;
yield return new WaitForFixedUpdate();
}
Debug.Log("进度设置完成");
//进度条完成 允许显示
_async.allowSceneActivation = true;
}
}
二、异步加载场景代码(Win)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; //引入命名空间
using UnityEngine.SceneManagement;//引入命名空间
public class S2Manager : MonoBehaviour
{
public Animation anim;
public Button button;
//UI进度条
public Slider _proSlider; //滑动条
//目的是对场景进行控制 获取进度值 和允许显示
private AsyncOperation _async;
//UI应该达到的进度
private int _currProgress;
//1. 获取滑动条
//协同加载(异步加载 不断获取进度值 经过计算赋值给滑动条)
// Use this for initialization
void Start()
{
_currProgress = 0;
_async = null;
}
public void Load()
{
StartCoroutine(LoadScene());
}
IEnumerator LoadScene()
{
anim.Play();
yield return new WaitForSeconds(1);
_proSlider.gameObject.SetActive(true);
while (_proSlider.value<0.7F)
{
_proSlider.value += 0.002F;
yield return new WaitForFixedUpdate();
}
Debug.Log("开始加载场景");
//异步加载
_async = SceneManager.LoadSceneAsync("Main"); //跳转场景为S3
_async.allowSceneActivation = false;
while (_async.progress<0.9F)
{
_proSlider.value += 0.002F;
yield return new WaitForFixedUpdate();
}
Debug.Log("场景准备完场");
while (_proSlider.value < 1)
{
_proSlider.value += 0.002F;
yield return new WaitForFixedUpdate();
}
Debug.Log("进度设置完成");
//进度条完成 允许显示
_async.allowSceneActivation = true;
}
}
三、总结
区别:如果win编辑器下运行的话_async.progress<0.9F这个while循环只会执行两次,在安卓下运行的话会一直执行。
所以在Win编辑器下先预先加载点进度,然后等待场景加载,加载完成之后判断进度条是否跑满,如果没有跑满,把进度条跑满,然后转跳场景。