Search Unity

Changing global variables within switch statement

Discussion in 'Scripting' started by kilgore, Jul 14, 2009.

  1. kilgore

    kilgore

    Joined:
    Jan 6, 2009
    Posts:
    18
    I am having a problem changing a global variable in an if statement that is nested within a switch.

    Pseudo-Code Example:

    Code (csharp):
    1.  
    2. private var myBool:boolean = false;
    3.  
    4. function TriggerEvent() {
    5.  
    6. switch (value){
    7.      case 1:
    8.         if(!myBool){
    9.            FunctionOne();
    10.            myBool = true;
    11.         }
    12.         break;
    13.      case 2:
    14.         if(myBool){
    15.            FunctionTwo();
    16.            myBool = false;
    17.         }
    18.         break;
    19. }
    20. }
    21.  
    In this example I am attempting to toggle the global variable myBool on/off. Console traces the boolean as being changed to true when TriggerEvent is called. However if TriggerEvent is called again the switch statement acts like myBool is still false and case 1 is used. If the boolean is changed in the called functions everythings cool, but I find this odd. Has anyone else run into this issue, should if statements not be nested within switch statement?
     
  2. phuzzy

    phuzzy

    Joined:
    Feb 12, 2009
    Posts:
    31
    Are you re-instantiating the script that defines the boolean as false between sets?
     
  3. kilgore

    kilgore

    Joined:
    Jan 6, 2009
    Posts:
    18
    I just realized what I was doing wrong, I was thinking that the variable was global to all of my scene assets, but it only applies to the object it is attached to. For every object that the TriggerEvent calls its myBool is false at first. :) my bad