Unity3D, editable global variables?

2019-08-13 02:27发布

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?

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-13 02:58

If the values are supported types, are not accessed to often and would benefit from persistance between application runs, PlayerPrefs is sometimes a good place to keep some globals :)

查看更多
时光不老,我们不散
3楼-- · 2019-08-13 03:01

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.

查看更多
登录 后发表回答