赞
踩
首先创建一个Global.cs
使用单例用于存储场景的名字,便于后续脚本的调用,此脚本不必挂载在游戏物体上。
using UnityEngine;
using System.Collections;
public class Global : MonoBehaviour
{
private static Global instance;
public static Global GetInstance()
{
if (instance == null)
{
instance = new Global();
}
return instance;
}
public string loadName = "gameScenes";
}
使用UGUI简单创建下面场景,GameManager为空物体,挂载OnPress.cs
OnPress.cs 脚本很简单,只用于实现场景的切换
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class OnPress : MonoBehaviour
{
public void Go()
{
//Global.GetInstance().loadName = "gameScenes";
//Application.LoadLevel("LoadingScene");
SceneManager.LoadScene("LoadingScene");
}
}
接下来就会跳转到LoadingScene场景,简单界面设计如下:
在GameManager物体上绑定Loading.cs
在加载主场景的时候一般会在Loading界面中显示一个进度条来告知玩家当前加载的进度。在Unity中可以通过调用Application.LoadLevelAsync函数来异步加载游戏场景,通过查询AsyncOperation.progress的值来得到场景加载的进度。
Unity提供了手动切换场景的方法,把AsyncOperation.allowSceneActivation设为false就可以禁止Unity加载完毕后自动切换场景,详情查阅
http://blog.csdn.net/huang9012/article/details/38659011
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Loading : MonoBehaviour
{
public Slider m_Slider;
public Text m_Text;
// Use this for initialization
void Start()
{
StartCoroutine(loadScene());
}
IEnumerator loadScene()
{
int displayProgress = 0;
int toProgress = 0;
//AsyncOperation op = Application.LoadLevelAsync(Global.GetInstance().loadName);
AsyncOperation op = SceneManager.LoadSceneAsync(Global.GetInstance().loadName);
op.allowSceneActivation = false;
while (op.progress < 0.9f)
{
toProgress = (int)op.progress * 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
}
toProgress = 100;
while (displayProgress < toProgress)
{
++displayProgress;
SetLoadingPercentage(displayProgress);
yield return new WaitForEndOfFrame();
}
op.allowSceneActivation = true;
}
public void SetLoadingPercentage(int DisplayProgress)
{
m_Slider.value = DisplayProgress * 0.01f;
m_Text.text = DisplayProgress.ToString() + "%";
}
}
接下来实现背景音乐在切换场景后也能循环播放。
在GameManager物体上绑定music脚本
using UnityEngine;
using System.Collections;
public class music : MonoBehaviour
{
static music instance;
public static music GetInstance()
{
if (instance == null)
{
instance = FindObjectOfType<music>();
DontDestroyOnLoad(instance.gameObject);
}
return instance;
}
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
}
else if (this != instance)
{
Destroy(gameObject);
}
}
private AudioSource m_AudioSource;
// Use this for initialization
void Start()
{
m_AudioSource = gameObject.GetComponent<AudioSource>();
m_AudioSource.clip = Resources.Load("Sound/01") as AudioClip;
m_AudioSource.Play();
m_AudioSource.loop = true;
}
}
当进度条达到100%后,会切换到gameScenes场景。
需要注意的是:在 File->Build Settings中添加之前的三个场景!如下所示:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。