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;
    }
}

你可能感兴趣的:(unity,unity)