OnGUI 音频
首先,导入一段音频文件到工程中,并给Main Camara添加Audio Source,再在Audio Source属性值中寻找Audio Clip,添加我们导入的音频,记得将play on awake的勾取消。
然后,新建一个脚本,并绑定到Main Camara上。脚本如下:
using UnityEngine; namespace Assets { public class Audio : MonoBehaviour { public float Vol = 0.5f; //音量大小 private bool flag = true; //播放还是暂停 public AudioSource music; //声音源 // Use this for initialization private void Start() { music = gameObject.GetComponent<AudioSource>(); Vol = 0.5f; } //每一帧都会调用 private void OnGUI() { switch (flag) { //若flag=true;绘制播放按钮 case true: if (GUI.Button(new Rect(10, 10, 100, 50), "播放")) { //注意这是在播放按钮被点击之后才改变flag值,因为GUI是每一帧都重新绘制的,若放在此IF条件之外,那么flag每秒会变N次 flag = !flag; if (!music.isPlaying) music.Play(); } break; //若flag=false;绘制暂停按钮 case false: if (GUI.Button(new Rect(10, 10, 100, 50), "暂停")) { flag = !flag; if (music.isPlaying) music.Pause(); } break; } if (GUI.Button(new Rect(10, 60, 100, 50), "停止")) { flag = true; if (music.isPlaying) { music.Stop(); } } Vol = GUI.HorizontalSlider(new Rect(160, 10, 100, 50), Vol, 0.0f, 1.0f); GUI.Label(new Rect(160, 50, 100, 50), "Music Volume is " + (int) (Vol*100) + "%"); if (music.isPlaying) { music.volume = Vol; } } } }
转自:http://blog.csdn.net/xys289187120/article/details/6989328