• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

游戏开发

U3D用单例创建并永久化游戏对象

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1007/47.html

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

单例模式(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;
 
 

上篇:上一篇:U3D协同程序实现游戏中AI(自动行走和发现目标)
下篇:下一篇:Resources.load及AssetBundle.Load加载过程研究