基類單例類:
using UnityEngine;
using System.Collections;
public class SingleClass<T> : MonoBehaviour where T: MonoBehaviour{
private static T _instance;
/// <summary>
/// Gets the instance.
/// </summary>
/// <returns>The instance.</returns>
public static T GetInstance() {
if (_instance == null) {
GameObject obj = new GameObject();
obj.name = typeof(T).ToString();
_instance = obj.AddComponent<T>();
DontDestroyOnLoad(obj);
}
return _instance;
}
}
使用方法:(實例化一個管理音效的對象)
using UnityEngine;
using System.Collections;
public class AudioManager : MonoBehaviour {
#region variable
private static AudioSource bgmSource;
private static AudioManager _instance;
#endregion
#region Attributes
#endregion
public void PlayBackgroundMusic(string musicName, bool loop = false) {
bgmSource.clip = Resources.Load(musicName) as AudioClip;
bgmSource.loop = loop;
bgmSource.Play();
}
public void SetBackgroundMusicVol(float vol) {
bgmSource.volume = vol;
}
public void ChangeBackgroundMusicStatus() {
if (bgmSource.isPlaying) {
bgmSource.Pause();
} else {
bgmSource.UnPause();
}
}
public void PlayEffect(string effectName, float timer) {
GameObject obj = new GameObject();
obj.name = effectName;
AudioSource source = obj.AddComponent<AudioSource>();
source.clip = Resources.Load(effectName) as AudioClip;
source.playOnAwake = false;
source.Play();
Destroy(obj, timer);
}
public static AudioManager GetInstance() {
if (!_instance) {
GameObject obj = new GameObject();
obj.name = typeof(AudioManager).ToString();
bgmSource = obj.AddComponent<AudioSource>();
bgmSource.clip = Resources.Load("Sounds/background") as AudioClip;
bgmSource.playOnAwake = false;
_instance = obj.AddComponent<AudioManager>();
DontDestroyOnLoad(obj);
}
return _instance;
}
}