Unity3D利用单例创建并永久化游戏对象(单例模式的应用)

发表于2018-09-13
评论0 2.8k浏览
单例模式(Singleton Pattern):用来创建独一无二的,只能有一个实例的对象的入场券。

作用:有些对象我们只需要一个,比如:线程池、缓存、对话框、处理偏好设置、注册表等对象,这些对象只能有一个实例,如果制造出多个实例,就会导致很多问题产生,例如:程序行为异常、资源使用过量、或者是不一致的结果。

下面就给大家分享下如何利用单例创建并实现永久化游戏对象。

基类单例类:
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;
	}
}
来自:https://blog.csdn.net/virus2014/article/details/52924950

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引