Unity3D, editable global variables?

假如想象 提交于 2019-12-13 01:18:16

问题


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?


回答1:


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.




回答2:


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 :)



来源:https://stackoverflow.com/questions/14219314/unity3d-editable-global-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!