Unity3D,可编辑的全局变量? [英] Unity3D, editable global variables?

查看:899
本文介绍了Unity3D,可编辑的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我所知,使用全局变量的唯一可能性是将它们定义为static(C#中的const)。
是否有任何方法可以从另一个脚本访问和更改变量,而这两个脚本都访问同一个变量?

解决方案

这取决于情况和您的要求。在大多数情况下,有几种方法可行。

如果两个脚本都是从 MonoBehaviour 派生的并且处于活动状态,您可以使用非静态公共成员并使用 GameObject.Find (如果您经常需要它或将其作为参考存储只有当你依赖于这两个对象在同一场景中处于活动状态或通过调用

时才能扩展其生命周期。 a href =http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html?from=GameObject =nofollow noreferrer> DontDestroyOnLoad 。



如果您有普通对象, public static 应该是最方便的方法,但可以与单例模式结合使用。请注意, public const 仅适用于基元类型。如果你想授予只读访问结构或对象,你可以使用 public static readonly



在Unity中,我如何将值从一个脚本传递到另一个脚本?,以了解编码示例和 Unity3D单例经理类,以深入探讨 MonoBehaviour 实例的单例。


As far as I know, the only possibility to use global variables is to define them as static (const in C#). Is there any way to access and change a variable from another script, while both scripts access the same variable?

解决方案

It depends on the situation and your requirements. In most cases there are several ways to go.

If both scripts are derived from MonoBehaviour and are active you can take non-static public members and use GameObject.Find (store it as reference if you need it quite often or use drag and drop in Unity editor).

This does work only if you rely on that objects both objects are active within the same scene or have its life cycle extended by calling DontDestroyOnLoad.

If you have plain objects, public static should be the most convenient approach but can be combined with singleton pattern. Note that public const works on primitive types only. If you want to grant read only access to structs or objects you can use public static readonly.

Have a look at In Unity, how can I pass values from one script to another? for coding examples and Unity3D singleton manager classes for some in depth thoughts about singletons for MonoBehaviour instances.

这篇关于Unity3D,可编辑的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆