0. 背景
单例模式非常常见,在各种语言上都能见到,用处也十分广泛,前一篇文章有讲到python的两种单例模式。当然Unity中组件的单例模式用途也很广,例如游戏中各种Manager
, 使用StartCoroutine
, GetComponent
等方法的单例,本文简要讲述一下Unity中对于组件的单例模式如何构建。
1. 相同之处
首先既然是单例模式,也就符合单例的一些既定规则:
- 构造参数为私有;
- 存在static
的实例变量名instance
;
- 存在static
的方法-Instance
or GetInstance
,以获取instance
,若第一次获取instance
则需要new
一个实例。
2. 不同之处
- 既然是Unity
的组件Component
,在new
组件实例时: 先需要new GameObject
, 然后new Component
, 并把新建的组件实例挂载到GameObject
;
- 当然这个新建的GameObject
不能持久化到