• Unity3D 场景切换加载进度条实现


    需要三个场景,场景A,场景B,场景C;

    场景A:一个按钮,点击加载场景B;

    场景B:从A切换到C过度场景,加载进度条;

    场景C:目标场景;

    创建OnProgress.cs脚本:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    
    public class OnProgress : MonoBehaviour {
    
        public void OnBtnClick()
        {
            Debug.Log("clicked");
            Globe.nextSceneName = "MainScene";//目标场景名称
            SceneManager.LoadScene("Loading");//加载进度条场景
        }
    }

    创建一个panel,在panel下创建一个button,将OnProgress脚本挂载到canvas,点击button,设置button属性,绑定脚本方法,点击加号,选择canvas中刚才绑定脚本中的方法OnBtnClick。至此,A场景完成。

    创建B场景Loading:

    Loading场景由两部分组成,加载进度百分比和进度条:

    文本就不说了,说明下进度条的实现,进度条实际是一个Image,设置Image Type为filled,fill Method为horizonal,这里一定要添加source Image,否则下面的Image Type不会出来。

    另外说下添加图片,普通的图片添加到assets中不能直接添加到Source Image中,需要对图片进行设置,如下图:

     OK,再看进度条加载过程的实现:

    创建AsyncLoadScene脚本:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    using UnityEngine.SceneManagement;
    
    public class Globe
    {
        public static string nextSceneName;
    }
    
    public class AsyncLoadScene : MonoBehaviour
    {
        public Text loadingText;
        public Image progressBar;
    
        private int curProgressValue = 0;
    
        private AsyncOperation operation;
    
        // Use this for initialization
        void Start()
        {
            if (SceneManager.GetActiveScene().name == "Loading")
            {
                //启动协程
                StartCoroutine(AsyncLoading());
            }
        }
    
        IEnumerator AsyncLoading()
        {
            operation = SceneManager.LoadSceneAsync(Globe.nextSceneName);
            //阻止当加载完成自动切换
            operation.allowSceneActivation = false;
    
            yield return operation;
        }
    
        // Update is called once per frame
        void Update()
        {
    
            int progressValue = 100;
    
            if (curProgressValue < progressValue)
            {
                curProgressValue++;
            }
    
            loadingText.text = curProgressValue + "%";//实时更新进度百分比的文本显示  
    
            progressBar.fillAmount = curProgressValue / 100f;//实时更新滑动进度图片的fillAmount值  
    
            if (curProgressValue == 100)
            {
                operation.allowSceneActivation = true;//启用自动加载场景  
                loadingText.text = "OK";//文本显示完成OK  
    
            }
        }
    }

    将脚本挂在到Loading场景的camera上面。设置对象:

    这样进度条加载场景就完成了,C场景就不介绍了,就是你要跳转的目标场景。

  • 相关阅读:
    【原创】(四)Linux进程调度-组调度及带宽控制
    【原创】(三)Linux进程调度器-进程切换
    【原创】(一)Linux进程调度器-基础
    【原创】(十六)Linux内存管理之CMA
    【原创】(十五)Linux内存管理之RMAP
    【原创】(十四)Linux内存管理之page fault处理
    我是如何学习和工作的(3)
    亲人的离去、爱情与婚姻
    工作机会少有时反而是一件好事
    Hong Kong Azure / .NET club first meetup
  • 原文地址:https://www.cnblogs.com/hutuzhu/p/9804348.html
Copyright © 2020-2023  润新知