1. 程式人生 > >unity之使用協程非同步載入場景

unity之使用協程非同步載入場景

public class UnityScriptManage : MonoBehaviour
{
    public void CallCoroutine(IEnumerator routine)
    {
        StartCoroutine(routine);
    }
}


public class Test
{

    public void LoadScene(LoadSceneMode mode)
    {
    //呼叫了UnityScriptManage中的CallCoroutine
       GlobalComManage.Instance.UnityScript.CallCoroutine(LoadAsync(mode));
    }

    //呼叫此介面,執行了一次yield return async之後就不執行了。且async.progress輸出為0
private IEnumerator LoadAsync(LoadSceneMode mode) { async = SceneManager.LoadSceneAsync(sceneName, mode); async.allowSceneActivation = false; while (!async.isDone && async.progress < 0.8f) { yield return async; } } //呼叫此介面,協程正常呼叫,但是由於async.allowSceneActivation設定為false所以scene.isLoaded狀態一直為false,且由於async.allowSceneActivation設定為false之後,async.progress最後一直停留在0.9。
private IEnumerator LoadAsync(LoadSceneMode mode) { async = SceneManager.LoadSceneAsync(sceneName, mode); Scene scene = SceneManager.GetSceneByName(sceneName); async.allowSceneActivation = false; while (!scene.isLoaded) { yield return null
; } async.allowSceneActivation = true; async = null; } }

最後版本:把allowSceneActivation設定為false後,Unity就只會載入場景到90%,剩下的10%要等到allowSceneActivation設定為true後才載入

public class UnityScriptManage : MonoBehaviour
{
    public void CallCoroutine(IEnumerator routine)
    {
        StartCoroutine(routine);
    }
}


public class Test
{

    public void LoadScene(LoadSceneMode mode)
    {
       GlobalComManage.Instance.UnityScript.CallCoroutine(LoadAsync(mode));
    }
    private IEnumerator LoadAsync(LoadSceneMode mode)
    {
        async = SceneManager.LoadSceneAsync(sceneName, mode);
        async.allowSceneActivation = false;
        while (!async.isDone && async.progress < 0.8f)
        {
            yield return async;
        }
    }
    private IEnumerator LoadAsync(LoadSceneMode mode)
    {
        async = SceneManager.LoadSceneAsync(sceneName, mode);
        Scene scene = SceneManager.GetSceneByName(sceneName);
        async.allowSceneActivation = false;
        while (async.progress < 0.9f)
        {
            yield return null;
        }
        async.allowSceneActivation = true;
        while(!scene.isLoaded)
        {
            yield return null;
        }
        async = null;
    }
}