如何在没有单例的Unity3d中创建游戏范围的对象? [英] How to create game-wide object in Unity3d without singleton?
问题描述
Unity3d框架中是否有一种方法可以注册一个对象,游戏中所有场景中的所有实体都可以访问该对象而无需求助于单例模式(例如游戏状态对象)?
Is there a way in Unity3d framework to register an object that would be accessible to all entities in all scenes in the game without resorting to singleton pattern (like a game state object)?
推荐答案
您可以采用以下方法:
在创建GameObject的场景中,在附加到GameObject的MonoBehavior脚本中:
In the scene where the GameObject is created, in a MonoBehavior script attached to the GameObject:
- 在Awake()(或在编辑器中)中将游戏对象命名为"name = ..."
- 示例: myObject.name ="FindMeInEveryScene";
- 引用: https://docs.unity3d.com/ScriptReference/Object-name.html
- 示例: DontDestroyOnLoad(myObject);
- 引用: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
在同一场景和后续场景中,在附加到其他GameObjects的MonoBehavior脚本中.
In the same scene and in subsequent scenes, in MonoBehavior scripts attached to other GameObjects.
- 使用Start()中的GameObject.Find(...)查找对象
- 示例: globalGameObject = GameObject.Find("FindMeInEveryScene");
- 引用: https://docs.unity3d.com/ScriptReference/GameObject.Find.html
这将使您可以单例访问名为"FindMeInEveryScene"的GameObject.
This will allow you to access the GameObject named "FindMeInEveryScene" without a singleton.
将它们组合在一起...
To pull it all together...
GlobalGameObject.cs
// Attached to the GameObject that needs to be accessd by any other // GameObjects and needs to survive between loading scenes public class GlobalGameObject : MonoBehaviour { static bool gameObjectInitialized = false; void Awake() { if ( !gameObjectInitialized ) { gameObject.name = "FindMeInEveryScene"; DontDestroyOnLoad( gameObject ); gameObjectInitialized = true; } } }
UsingGameObject.cs
// Attached to GameObjects that need access to the GlobalGameObject public class UsingGameObject : MonoBehaviour { private GameObject globalGameObject = null; void Start() { globalGameObject = GameObject.Find( "FindMeInEveryScene" ); } }
这篇关于如何在没有单例的Unity3d中创建游戏范围的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!