Unity—Loading界面-異步加載場景


Loading界面-異步加載場景

Demo展示

1g


加載新場景時,需要加載大量模型外部文件等,比較耗時,又不能讓畫面卡住不動;

很多時候會做一個加載界面顯示讀條;

這個加載條是個UI物體,可以自行添加替換UI素材;


代碼

非常簡直,就不贅述了;

一個slider條,progress為異步百分比;

限制讀條3s結束,小於3s等待;

注意異步讀條progress到不了1,所以0.9判斷加載完成;

public class Loading : MonoBehaviour
{
    public string scenceName;
    
    AsyncOperation async;

    public Slider m_pProgress;

    private int progress = 0;

    private float time = 3f;
    private float startTime = 0;
    private void Start()
    {
        StartCoroutine(LoadScenes());
        startTime = Time.time;
    }

    IEnumerator LoadScenes()
    {
        int nDisPlayProgress = 0;
        async = SceneManager.LoadSceneAsync(scenceName);
        async.allowSceneActivation = false;
        while (async.progress < 0.9f)
        {
            progress = (int)async.progress * 100;
            while (nDisPlayProgress < progress)
            {
                ++nDisPlayProgress;
                m_pProgress.value = (float)nDisPlayProgress / 100;
                yield return new WaitForEndOfFrame();
            }
            
            yield return null;
        }

        progress = 100;
        while (nDisPlayProgress < progress)
        {
            ++nDisPlayProgress;
            m_pProgress.value = (float)nDisPlayProgress / 100;
            yield return new WaitForEndOfFrame();
        }
        
        float temp = Time.time - startTime;
        if (temp < time)
            yield return new WaitForSeconds(time - temp);
        
        async.allowSceneActivation = true;
    }
}

測試代碼:

加載場景時,記在loading界面,設置需要加載的場景名稱;

public class MainScence : MonoBehaviour
{
    public Button btnLoad;
    void Start()
    {
        btnLoad.onClick.AddListener(OnLoadFight);
    }

    private void OnLoadFight()
    {
        GameObject go = Instantiate(Resources.Load<GameObject>("Loading"), transform);
        go.GetComponent<Loading>().scenceName = "FightScence";
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM