Search Unity

testing for undefined variables...?

Discussion in 'Scripting' started by Unclet, Jul 27, 2007.

  1. Unclet

    Unclet

    Joined:
    Apr 12, 2007
    Posts:
    92
    Background:

    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...

    What am I doing wrong?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You could actually put this object in all scenes, and destroy it if one already exists. That is, something like:


    Code (csharp):
    1.  
    2. static var singleton : YourClassName;
    3.  
    4. function Start() {
    5. if (singleton) Destroy(gameObject);
    6.  
    7. singleton = this;
    8. }
    9.  
    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.

    Hope this helps!
     
  3. Unclet

    Unclet

    Joined:
    Apr 12, 2007
    Posts:
    92
    I think I can answer my own question :)

    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:
    Code (csharp):
    1.  
    2. //globals.js
    3.  
    4. static var foo : STUFF;
    5.  
    6. class STUFF{
    7.     var thing1: int;
    8.     var thing2: float;
    9.     var thing3 = "Whoopee";
    10. }
    11.  
    12. function Start(){
    13.     DontDestroyOnLoad(this);
    14.     foo = new STUFF();
    15.     foo.thing3 = "Grrrrrreat";
    16. }
    17.  
    18.  
    19. -----
    20.  
    21. //script in object on random level that would like to use the globals:
    22.  
    23. var bar : STUFF;
    24.  
    25.  
    26.  
    27. function Start () {
    28.     if(!globals.foo)
    29.         {
    30.         bar = new STUFF();
    31.         }
    32.     else
    33.         {
    34.         bar = globals.foo;
    35.         }
    36.  
    37. }
    38.  
    if the initial scene with the globals is in memory, bar.thing3 will hold "Grrrrreat" otherwise it hold the default class value of "Whoopee".
     
  4. Unclet

    Unclet

    Joined:
    Apr 12, 2007
    Posts:
    92
    Oh, that's an idea, too. Thanks!