- Home /
How do you achieve variables and functions that are global between scenes? What is the BEST way?
(Static functions/variables) VS (a reference to a GameObject)
Should I use static functions? Or should I use a reference to a GameObject? Is there another better way all together?
If I have data and functions I want to be able to access and change/execute from anywhere (including in-between scenes), should I just make those static and do things like GameManager.numPlayers
which lets me do this as well (from anywhere): GameManager.numPlayers = 1
Or should I reference an instance of a script attached to a GameObject as a component?
My understanding of the latter way is: a reference to a kind of "global GameObject
" would need to be declared at the header of each script like this: private var globalGameObject : GameObject;
and then defined in Start()
like this: globalGameObject = FindObjectOfType( GlobalGameObject );
and then used in other functions (in the same script) like this: gameObject.GetComponent( GlobalGameObject ).numPlayers
Note: ...this "`GlobalGameObject.js`" script would have had to have been attached to a GameObject
that had had DontDestroyOnLoad( transform.gameObject );
called upon it.
Therefore the static variables/functions seem to have more syntactic sugar. Especially because of the fact that there's no adding as a Component
to an instantiated GameObject
(that has had DonstDestroyOnLoad()
called upon it). Static variables like GameManager.numPlayers
seem to work and retain their values throughout gameplay. Is there any danger in using static variables defined in non-attached scripts like this?
Is there a better way all together?
How do you achieve variables and functions that are global between scenes?
Let me update this question: I forgot to mention that sometimes, even when using static variables/functions, the script is being attached to a "global GameObject
" because some variables require setup in a for
loop. The only way I know to achieve this for
loop is by attaching as a Component
to an instantiated GameObject
.
Update 2: I am using JavaScript.
Answer by Kryptos · May 15, 2012 at 09:33 AM
Take a look at the singleton pattern. There are lots of topics in Unity Answers and Forums. For example:
Singletons with coroutines (Unity Answers)
Singleton (Unify Community)
Component-based singleton (Unity Answers)
I recommend using a component-based singleton:
You can have several components on this persistent game object that deal with different parts of your game (game logic, players management, audio, etc.).
These components (and more specifically
MonoBehaviour
s) will receive Unity events such asOnEnable
,OnLevelWasLoaded
andOnApplicationQuit
(and evenUpdate
which can be useful for managing the game logic).