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?
相关问题
- Unity - Get Random Color at Spawning
- Unity3D WebGL Headless not rendering
- Store data and global variables using the Applicat
- Unity3D loading resources after build
- Load Image from Stream/StreamReader to Image OR Ra
相关文章
- Programmatically setting and saving the icon assoc
- Omnisharp in VS Code produces a lot of warnings ab
- Call non-static methods on custom Unity Android Pl
- How can a game created in Unity can run on an Andr
- How to add Persistent Listener to Button.onClick e
- Placing an object in front of the camera
- javascript setInterval() and Variable Scope
- Connecting Unity3d Android application to ActiveMQ
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 :)
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 thatpublic const
works on primitive types only. If you want to grant read only access to structs or objects you can usepublic 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.