游戏开发中最常用的3种设计模式分别是:单例模式、观察者模式、对象池模式。接下来一一对它们进行介绍。
单例模式
单例模式指的是全局只有一个管理器(游戏管理器、音效管理器、UI管理器),任何脚本都能随时调用GameManager.Instance,不用到处找物体。
以下是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Test :MonoBehaviour { public static Test Instance { get; private set; } private void Awake() { if(Instance != null) { Destory(gameObject); return; } Instance = this; } }
|
观察者模式
观察者模式就是先让观察者订阅被观察者的事件,被观察者状态变了,就统一广播通知,所有订阅过的观察者自动触发自己的方法。
以下是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public void class PopAudioPlayer : MonoBehaviour { private AudioSource _audioSource;
private void Awake() { _audioSource = GetComponent<AudioSource>(); } private void OnEnable() => BubblePop.OnAnyBubblePoped += PlayPopAudio; private void OnDisable() => BubblePop.OnAnyBubblePoped -= PlayPopAudio; private void PlayPopAudio() { _audioSource.Play(); } }
|
1 2 3 4 5 6 7 8 9
| public void class BubblePop : MonoBehaviour { public static event Action OnAnyBubblePopped; private void OnMouseDown() { OnAnyBubblePopped?.Invoke(); } }
|
对象池模式
对象池模式就是提前创建一批对象放进 “池子” 里,要用就拿、用完不销毁直接放回去重复用,避免不停 Instantiate / Destroy 卡帧。
以下是一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class ObjectPool { private Queue<GameObject> _poolQueue = new Queue<GameObject>(); private GameObject _prefab; public ObjectPool(GameObject prefab) { _prefab = prefab; for(int i = 0; i < 10; i ++) { GameObject obj = GameObject.Instantiate(_prefab); obj.SetActive(false); _poolQueue.Enqueue(obj); } } public GameObject Get() { if(_poolQueue.Count == 0) { GameObject obj = GameObject.Instantiate(_prefab); obj.SetActive(false); _poolQueue.Enqueue(obj); } GameObject take = _poolQueue.Dequeue(); take.SetActive(true); return take; } public void Recycle(GameObject obj) { obj.SetActive(false); _poolQueue.Enqueue(obj); } }
|