Unity wiki 的 Singleton 是如何工作的?
How does Unity wiki's Singleton work?
我的场景中有一个 "manager" 游戏对象,上面附加了一个 Manager
脚本组件。
我需要这个 Manager
脚本是一个 单例 因为有多个管理器是没有意义的。
我使用了单例实现from the Unity wiki。
我有两个问题:
- 为什么要创建一个新的GameObject然后用
GameObject.AddComponent<T>()
实例化单例?为什么不直接做 new T()
?
- 我有
protected
我的 Singleton
和 Manager
class 构造函数。除了他们自己,没有人应该能够实例化这些 classes。 Unity Editor 如何实例化它们?
正如评论所说:
MonoBehaviour classes 不能用 new T()
实例化,因为 GameObject 组件的工作方式:它们 必须 附加到一个游戏对象!因此,GameObject class 提供了一种实例化附加到该 GameObject 的新 MonoBehaviour 的方法:AddComponent<T>()
可能通过反射操作(其他 MonoBehaviour 方法,例如 Start()
和 Update()
aren't exactly invoked with reflection,不是运行时的每一帧,但很容易将它们进行比较;它是不透明和神奇的,并且有 显着 开销,所以它也可能是反思)。
完全阻止构造函数被调用可能只会破坏一切,所以不要再费心去保护它了。由于 AddComponent 的工作方式,通过反射调用构造函数,您实际上无法 阻止 创建新实例,但您可以检测到它发生并采取一些措施。我的首选方式是脚本运行 "oh, an instance already exists and its not me" 并自行销毁。
此外,由于组件可能需要其他组件(RigidBody 需要 Collider,MonoBehaviours can specify their own requirements as well) which is specified through an attributes, when AddComponent<T>()
is called to add the one component, it will search the class attributes to see if there are any [RequireComponents]
specified and add them too, automatically. This would also be done through reflection。
我的场景中有一个 "manager" 游戏对象,上面附加了一个 Manager
脚本组件。
我需要这个 Manager
脚本是一个 单例 因为有多个管理器是没有意义的。
我使用了单例实现from the Unity wiki。
我有两个问题:
- 为什么要创建一个新的GameObject然后用
GameObject.AddComponent<T>()
实例化单例?为什么不直接做new T()
? - 我有
protected
我的Singleton
和Manager
class 构造函数。除了他们自己,没有人应该能够实例化这些 classes。 Unity Editor 如何实例化它们?
正如评论所说:
MonoBehaviour classes 不能用 new T()
实例化,因为 GameObject 组件的工作方式:它们 必须 附加到一个游戏对象!因此,GameObject class 提供了一种实例化附加到该 GameObject 的新 MonoBehaviour 的方法:AddComponent<T>()
可能通过反射操作(其他 MonoBehaviour 方法,例如 Start()
和 Update()
aren't exactly invoked with reflection,不是运行时的每一帧,但很容易将它们进行比较;它是不透明和神奇的,并且有 显着 开销,所以它也可能是反思)。
完全阻止构造函数被调用可能只会破坏一切,所以不要再费心去保护它了。由于 AddComponent 的工作方式,通过反射调用构造函数,您实际上无法 阻止 创建新实例,但您可以检测到它发生并采取一些措施。我的首选方式是脚本运行 "oh, an instance already exists and its not me" 并自行销毁。
此外,由于组件可能需要其他组件(RigidBody 需要 Collider,MonoBehaviours can specify their own requirements as well) which is specified through an attributes, when AddComponent<T>()
is called to add the one component, it will search the class attributes to see if there are any [RequireComponents]
specified and add them too, automatically. This would also be done through reflection。