更新时间:2023-11-29 21:57:52
像往常一样:它依赖。我用这两种单件,组件连接到游戏对象
,而不是从 MonoBehaviour
派生单独的类。 IMO的整体问题是如何被实例绑定到场景,游戏对象的lifcycle,...而不是有时会忘记它是更方便的一个组成部分特别引用其他 MonoBehaviour
物体更容易,更安全。
Like always: it depends. I use singletons of both kinds, components attached to GameObject
and standalone classes not derived from MonoBehaviour
. IMO the overall question is how are instances bound to the lifcycle of scenes, game objects, ... And not to forget sometimes it is more convenient to have a component especially referencing other MonoBehaviour
objects is easier and safer.
开始
被称为还是得执行更新$行动C $ C>或其它方法。然后,我实现它们的成分,并将其安装到能承受住加载新的场景游戏对象。
Start
is called or have to perform actions in Update
or other methods. Then I implement them as component and attach them to a game object that survives loading new scenes.我设计了基于组件的单身两部分(2型):持久游戏对象
名为主
,其持有所有部件和名为 MainComponentManager
管理它的扁平单(1型)。一些演示code:
I designed component based singletons (type 2) with two parts: a persistent GameObject
called Main
, which holds all components and a flat singleton (type 1) called MainComponentManager
for managing it. Some demo code:
public class MainComponentManger {
private static MainComponentManger instance;
public static void CreateInstance () {
if (instance == null) {
instance = new MainComponentManger ();
GameObject go = GameObject.Find ("Main");
if (go == null) {
go = new GameObject ("Main");
instance.main = go;
// important: make game object persistent:
Object.DontDestroyOnLoad (go);
}
// trigger instantiation of other singletons
Component c = MenuManager.SharedInstance;
// ...
}
}
GameObject main;
public static MainComponentManger SharedInstance {
get {
if (instance == null) {
CreateInstance ();
}
return instance;
}
}
public static T AddMainComponent <T> () where T : UnityEngine.Component {
T t = SharedInstance.main.GetComponent<T> ();
if (t != null) {
return t;
}
return SharedInstance.main.AddComponent <T> ();
}
这要注册为主
组件现在单身其他单看这样的:
Now other singletons that want to register as Main
component just look like:
public class AudioManager : MonoBehaviour {
private static AudioManager instance = null;
public static AudioManager SharedInstance {
get {
if (instance == null) {
instance = MainComponentManger.AddMainComponent<AudioManager> ();
}
return instance;
}
}