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

unity的异步加载

程序员文章站 2022-04-03 15:57:37
...

注意点

AsyncOperation的progress(0-1)属性在isDone为false时,最大加载到0.9就会暂停,直到isDone为true时才会继续加载0.9-1.0的这10%,而isDone为true或fasle的标志为是: 当allowSceneActivation = false,isDone为false ,allowSceneActivation = false 的作用是让场景不会在加载完成后自动跳转到下一个场景,   当allowSceneActivation = true,isDone为true,或者progress = 1.0时 isDone = true

示例

(1)代码(没有用到isDone)

 public Slider progressUI; //进度条
    public Text progressValue; //百分比描述文本
    private AsyncOperation prog;  // 异步操作类
    void Start()
    {
        StartCoroutine(LoadAsycLevel()); //启动协同
    }
    // 设置进度条值
    private void SetProgressValue(int value)
    {
        progressUI.value = value;
        progressValue.text =value + "%";
    }
 
    // 异步加载场景
    IEnumerator LoadAsycLevel()
    {
        //异步加载场景
         prog = SceneManager.LoadSceneAsync("CG");
        //如果加载完成,也不进入场景
        prog.allowSceneActivation = false;
        //最终的进度
        int toProgress = 0;
        //显示的进度
        int showProgress = 0;
        //测试了一下,进度最大就是0.9
        while (prog.progress < 0.9f)
        {
            //toProcess具有随机性
            toProgress = (int)(prog.progress * 100);
            while (showProgress < toProgress)
            {
                showProgress++;
                SetProgressValue(showProgress);
                yield return new WaitForEndOfFrame(); //等待一帧
            }
        }
        toProgress = 100;
 
        while (showProgress < toProgress)
        {
            showProgress++;
            SetProgressValue(showProgress);
            yield return new WaitForEndOfFrame(); //等待一帧
        }
        prog.allowSceneActivation = true;  //如果加载完成,可以进入场景
    }

(2)代码(用到isDone)

 private Text progress;
    //进度条的数值
    private float progressValue;
    //进度条
    private Slider slider;
    [Tooltip("下个场景的名字")]
    public string nextSceneName;
   //创建异步加载类
    private AsyncOperation async = null;
 
    private void Start() {
        progress = GetComponent<Text>();
        slider = FindObjectOfType<Slider>();
   //启用协程 
        StartCoroutine("LoadScene");
    }
 
    IEnumerator LoadScene() {
        async = SceneManager.LoadSceneAsync(nextSceneName);
        //即使加载完也不跳场景
        async.allowSceneActivation = false;
        while (!async.isDone) {
            if (async.progress < 0.9f)
                progressValue = async.progress;
            else
                progressValue = 1.0f;
 
            slider.value = progressValue;
            progress.text = (int)(slider.value * 100) + " %";
 
            if (progressValue >= 0.9) {
                progress.text = "按任意键继续";
                if (Input.anyKeyDown) {
                    async.allowSceneActivation = true;
                }
            }
            yield return null;
        }
    }