为应用声明一个全局的音效管理脚本
step1:在最初一个Scene添加一个全局AudioSource
using UnityEngine;
using System.Collections;
public class AudioManager : MonoBehaviour {
private static AudioManager instance= null;
[HideInInspector]
public AudioSource audioMgr;
private AudioClip ac;
private string curMusicName = "";
private bool allowPlay = true;
public static AudioManager getInstance(){
return instance;
}
void Awake() {
if (instance != null && instance != this) {
Destroy(this.gameObject);
} else {
instance = this;
audioMgr = GetComponent(typeof(AudioSource)) as AudioSource;
}
DontDestroyOnLoad(this.gameObject);
}
public bool getAllowPlay() {
return allowPlay;
}
public void setAllowPlay(bool allowPlayNew) {
allowPlay = allowPlayNew;
}
public void Play(string fileName) {
if(!allowPlay) {
return ;
}
if (!fileName.Equals(curMusicName)) {
ac = Resources.Load("audio/"+fileName) as AudioClip;
audioMgr.clip = ac;
audioMgr.volume = 1f;
audioMgr.Play();
curMusicName = fileName;
}
}
public void Stop() {
audioMgr.Stop();
curMusicName = "";
}
}
step2:在最初Scene添加SoundHolder,SoundWorldHolder
step3:
背景音:
AudioManager.getInstance().setAllowPlay(true);
AudioManager.getInstance().Play(“welcome_music”);
AudioManager.getInstance().Stop();
音效:
SoundManager.getInstance().setAllowPlay(false);
SoundManager.getInstance().Clean();