欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 异步加载场景

程序员文章站 2022-04-03 12:28:51
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class loadingAsync : MonoBehaviour {
    private AsyncOperation m_Ao;
    public string loadSceneName;
    private bool isLoading;
    public Text processText;
	// Use this for initialization
	void Start ()
    {
	
}

// Update is called once per frame
void Update ()
{
	
}
private void loading()
{
    StartCoroutine("loadScene");
}
IEnumerator loadScene()
{
    int startProcess = 0;
    int endProcess = 100;
    while (startProcess < endProcess)
    {
        startProcess++;
        showProcess(startProcess);         
        if (isLoading == false)
        {
            m_Ao = SceneManager.LoadSceneAsync(loadSceneName);
            
            m_Ao.allowSceneActivation = false;
            
            isLoading = true;
        }
        yield return new WaitForEndOfFrame();
    }
    if (startProcess == 100)
    {
        StopCoroutine("loadScene");//停止协程  应该用字符串,这样才能真正的停止协程,那么开启协程也应该用字符串
        m_Ao.allowSceneActivation = true;
    }
}
private void showProcess(int process)
{
    processText.text = process.ToString() + "%";
}

}