unitybgmusic

来源:互联网 发布:连云港天马网络 编辑:程序博客网 时间:2024/06/05 18:11

http://unity3d.9tech.cn/news/2013/1107/38476.html

今天有人问我切换场景时背景音乐不能正常播放,于是写了个例子简单测试下,具体如下:

首先创建两个场景,为了 区分两个场景的不同,我们给第一个场景中加一个Cube,并新建一个空物体GameObject,附加音频组件AudioSource,拖放音频文件上 去,为保证这个空物体在场景切换时不被销毁,我们需要使用DontDestroyOnLoad(object)方法,新建一个C#脚本TestAudio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using UnityEngine;
using System.Collections;
 
<span style="white-space:pre">    </span>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进行切换场景

1
2
3
4
5
6
7
8
if(GUI.Button(newRect(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中的代码

1
2
3
4
5
6
7
8
9
public GameObject obje;
GameObject obj=null;
// Use this for initialization
void Start () {
    obj = GameObject.FindGameObjectWithTag("sound");
    if(obj==null) {
        obj = (GameObject)Instantiate(obje);
    }  
}
拖放预设GameObject到obj


运行,切换场景时,背景音乐不间断播放

接下来可以对背景音乐进行控制,如播放,暂停,停止

1
2
3
4
5
6
7
8
9
if(GUI.Button(newRect(10,90,120,30),"Pause")) {
    obj.audio.Pause();
}
if(GUI.Button(newRect(10,130,120,30),"Stop")) {
    obj.audio.Stop();
}
if(GUI.Button(newRect(10,50,120,30),"Play")) {
    obj.audio.Play();
}

0 0
原创粉丝点击