连连看项目实战之四(异步加载进度条)

推荐阅读:

      在玩游戏过程中,从一个场景加载到另一个场景,我们会发现,往往不是直接切换过去的,而是停留在当前界面,加载下一场景资源,等下一场景加载完毕就切换至加载完成得场景。在轻度一点的游戏上我们往往感受不到它的存在,但是在重度游戏上,往往表现很明显。因为在场景切换中,需要加载的资源可能很大,需要一定的时间,为了照顾玩家的体验,往往在场景中制作一个进度条显示加载进度。
      在unity中新建一个场景,并添加如下组件(loadBg和loadProcess是两张一模一样的图片,包括位置信息都一样):
在这里插入图片描述
      接下来,我们需要对loadProcess组件进行修改,首先更改它的颜Color属性,Image Type:Filled,Fill Method : Horizontal,如下:
在这里插入图片描述
界面完成了,下面是代码部分:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
 
public class MyMenuUI : MonoBehaviour {
    //新游戏按钮
    public Button newGameButton;
    //加载界面
    public GameObject loadPanel;
    //滑动进度条
    public Image progressImg;
    //不断更新的进度值
    private int curProgressValue = 0;
    //进度显示百分比
    public Text proText;
 
    //异步加载进程
    private AsyncOperation async;
 
    void Start()
    {
        loadPanel.SetActive(false);//一开始禁用加载层。
    }
 
   //点击按钮跳场景
    public void NewGamePressed()
    {
        StartCoroutine(LoadScene());//调用加载场景的协程
        loadPanel.SetActive(true);//启用加载界面
    }
 
  //协程加载场景
    IEnumerator LoadScene()
    {
        async = SceneManager.LoadSceneAsync("TankGameScene");
        async.allowSceneActivation = false;//此处将允许自动场景加载禁用,防止到90%时自动跳转到新场景。
		yield return async;
    }
 
    void Update()
    {
        if (async == null)
        {
            return;//进程为空,跳出该函数
        }
        //总的进度值
        int progressValue = 100;
        if (curProgressValue < progressValue)
        {
            curProgressValue++;
        }
        proText.text = "Loading "+curProgressValue + "%";//实时更新进度百分比的文本显示
        progressImg.fillAmount = curProgressValue / 100f;//实时更新滑动进度图片的fillAmount值
        if (curProgressValue == 100)
        {
            async.allowSceneActivation = true;//启用自动加载场景
            proText.text = "OK";//文本显示完成OK
        }
    }
}

      上面代码注释很详细,这里我就不一一解说了,有不懂的可以公众号后台留言,专业人士为你解答~

原文地址:https://www.cnblogs.com/shirln/p/10330736.html