今天有人问我切换场景时背景音乐不能正常播放,于是写了个例子简单测试下,具体如下:
首先创建两个场景,为了区分两个场景的不同,我们给第一个场景中加一个Cube,并新建一个空物体GameObject,附加音频组件AudioSource,拖放音频文件上去,为保证这个空物体在场景切换时不被销毁,我们需要使用DontDestroyOnLoad(object)方法,新建一个C#脚本TestAudio
using UnityEngine;
using System.Collections;
public class TestAudio : MonoBehaviour {
// Use this for initialization
void Start () {
DontDestroyOnLoad(this.gameObject);
}
// Update is called once per frame
void Update () {
}
}
将此脚本拖放给GameObject,保持GameObject不被Destory掉
再建一个C#脚本TestAudio2,用来绘制GUI进行切换场景
if (GUI.Button(new Rect(10,10,120,30),"load level")) {
if (Application.loadedLevelName=="test1") {
Application.LoadLevel("test2");
}
else {
Application.LoadLevel("test1");
}
}
在这里我们拖放给相机就可以了
另外要注意一个地方,当我们从第一个场景test1切换到test2的时候没有问题,但是从test2切换回test1的时候,场景里会多出一个GameObject,此时会出现两个声音(一个是test1里重新生成的,另一个是我们之前没有销毁的),为了解决这个问题我们把GameObject设为预设,并加个标签sound
编辑TestAudio2中的代码
public GameObject obje;
GameObject obj=null;
// Use this for initialization
void Start () {
obj = GameObject.FindGameObjectWithTag("sound");
if (obj==null) {
obj = (GameObject)Instantiate(obje);
}
}
拖放预设GameObject到obje
运行,切换场景时,背景音乐不间断播放
接下来可以对背景音乐进行控制,如播放,暂停,停止
if (GUI.Button(new Rect(10,90,120,30),"Pause")) {
obj.audio.Pause();
}
if (GUI.Button(new Rect(10,130,120,30),"Stop")) {
obj.audio.Stop();
}
if (GUI.Button(new Rect(10,50,120,30),"Play")) {
obj.audio.Play();
}
本来想上传源码来着,不知道从哪上传,如果想要的话,可以找我要