版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lijianfex/article/details/78238759
制作游戏经常要实现两个场景的切换,但由于加载场景需要一定时间,所以为了优化玩家体验,在第一个场景中制作一个进度条显示加载进度。
现在就在unity中实现,go go!
打开unity,新建场景 GameMainUI,制作一个开始游戏的界面如下图。
play与exit都为按钮,在text上加Button组件即可制作。
现在制作进度条,在canvas下创建Panel改为LoadingPanel,在LoadingPanel下创建image改为loadingbg作为进度条的加载背景图,调为红色。
在loadingbg下添加image组件progress作为滑动进度条,添加text组件proText作为显示加载完成百分比。
image组件progress,image Type:Filled , Fill Method : Horizontal
颜色自定,与背景图区分,现在拖动Fill Amount就可以看到效果
text组件proText效果如下:
界面完成,现在是代码部分:
创建C#脚本 MyMenuUI.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MyMenuUI : MonoBehaviour {
//新游戏按钮
public Button newGameButton;
//退出按钮
public Button exitButton;
//加载界面
public GameObject loadPanel;
//滑动进度条
public Image progressImg;
//进度显示百分比
public Text proText;
//异步加载进程
private AsyncOperation async;
//不断更新的进度值
private int curProgressValue = 0;
void Start()
{
loadPanel.SetActive(false);//一开始禁用加载层。
}
/// <summary>
/// Play按钮点击事件
/// </summary>
public void NewGamePressed()
{
StartCoroutine(LoadScene());//调用加载场景的协程
loadPanel.SetActive(true);//启用加载界面
}
/// <summary>
/// 加载场景协程
/// </summary>
/// <returns></returns>
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
}
}
/// <summary>
/// EXIT按钮点击事件
/// </summary>
public void ExitGamePressed()
{
//退出整个游戏
Application.Quit();
}
}
将MyMenuUI.cs挂在到MainCamera上,并绑定相关组件
现在运行可能会出问题,可能是第二场景没添加到Scence in build,我的是新建了名为 TankGameScene 的场景,你可以自己制作要加载的第二个场景,保存好。
打开File---->Build Setting
点击Add Open Scences 确保切换加载的两个场景都被加载
现在到第一场景,点击运行后,点击Play按钮,就能看到效果!
nice nice!
这是我的第一篇博文,有幸被你看到,第一个留言的访客,写下你的QQ,发个小红包给你,哈哈!
如果有问题欢迎提出,互相交流学习!Go GO!继续成长之路。
工程下载地址:链接:http://pan.baidu.com/s/1pLyrL2N 密码:2lq8