情景一:在整个游戏中播放一个背景音乐,反复重复播放,可以暂停播放和继续播放。
解决方案:首先在场景中首先创建一个空物体Audio,设置其Tag值为"Audio",在空物体上添加组件:AudioSource,AudioListener(Component->Audio->AudioSource;Componet->Audio->AudioListener),将音乐资源(例如:.mp3文件)拖到AudioSource的AudioClip项中,在PlayOnAwake、Loop项前打勾,同时需要注意将每个Scene的所有摄像机(或其它物体)的AudioListener前面的√去掉。在Audio上添加脚本,代码如下:
using UnityEngine;
using System.Collections;
public class Audio : MonoBehaviour {
// Use this for initialization
public GameObject VolumeSlider;
GameObject audio;
void Start () {
GameObject [] audioes = GameObject.FindGameObjectsWithTag ("Audio");
if (audioes.Length == 2) {//当第二个出现时将自身销毁
Destroy (this.gameObject);
}
DontDestroyOnLoad (this.gameObject);
audio = GameObject.FindGameObjectWithTag ("Audio");
}
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {//按A键,音乐暂停或继续播放
if (audio.GetComponent<AudioSource>().isPlaying) {
audio.GetComponent<AudioSource>().Pause();
}
else {
audio.GetComponent<AudioSource>().Play();
}
}
}
}
欢迎大家批评指正,在此多谢各位不吝赐教!