1

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?

Sam
  • 7,252
  • 16
  • 46
  • 65
nauti
  • 1,396
  • 3
  • 16
  • 37

2 Answers2

4

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.

Community
  • 1
  • 1
Kay
  • 12,918
  • 4
  • 55
  • 77
0

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