I want to keep some globals in a “DontDestroyOnLoad” script that is loaded in the first scene of the game. Stuff like input preferences, etc.
Since the gameObject it is attached to is loaded in the initial scene, it’s not part of later scenes as it is “already there” – this makes sense.
The problem occurs with workflow – how do I run and test a later scene without going back to the initial scene in order to load the globals script?
I thought maybe I just test for undefined values, and substitute default values if the globals were not present, but Unity doesn’t seem to like this approach…
You could actually put this object in all scenes, and destroy it if one already exists. That is, something like:
static var singleton : YourClassName;
function Start() {
if (singleton) Destroy(gameObject);
singleton = this;
}
When testing, the object in the current scene will be set as the singleton. When you go to the scene from a scene that already contains this object - and YourClassName.singleton is already set - it will self destruct.
The key for me is the realization that scripts are available even if they are not attached to an active object in the scene.
so:
//globals.js
static var foo : STUFF;
class STUFF{
var thing1: int;
var thing2: float;
var thing3 = "Whoopee";
}
function Start(){
DontDestroyOnLoad(this);
foo = new STUFF();
foo.thing3 = "Grrrrrreat";
}
-----
//script in object on random level that would like to use the globals:
var bar : STUFF;
function Start () {
if(!globals.foo)
{
bar = new STUFF();
}
else
{
bar = globals.foo;
}
}
if the initial scene with the globals is in memory, bar.thing3 will hold “Grrrrreat” otherwise it hold the default class value of “Whoopee”.