- Home /
 
 
               Question by 
               superluigi · Mar 08, 2014 at 09:56 PM · 
                javascriptif-statements  
              
 
              help understanding variables created in an if statement vs up top
While writing code I noticed how this doesn't work
 if(Input.GetButtonDown("P2hp"))
         {
             var hpRayStall = Time.time + 1;
         }
         if(hpRayStall <= Time.time)
         {
             var hpRay = Physics.Raycast(lp.transform.position, transform.TransformDirection(Vector3.right), 2);
         }
         if(hpRay)
         {
             sceneManager.GetComponent(SceneManagerScript).p1HP -= 6;
         }
 
               However this did despite being the same thing, the only difference being where hpRayStall was created (I believe the proper term is declared)
 var hpRayStall : float;
 
 function Update()
 if(Input.GetButtonDown("P2hp"))
         {
             hpRayStall = Time.time + 1;
         }
         if(hpRayStall <= Time.time)
         {
             var hpRay = Physics.Raycast(lp.transform.position, transform.TransformDirection(Vector3.right), 2);
         }
         if(hpRay)
         {
             sceneManager.GetComponent(SceneManagerScript).p1HP -= 6;
         }
 
              
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Eric5h5 · Mar 08, 2014 at 10:02 PM
It's called scope; variables declared outside a function are global in scope. When you declare hpRayStall inside Update, it only exists in that function, and is destroyed when Update ends. So it's declared again from scratch the next Update, instead of re-using the existing value. Note that if you're declaring hpRayStall locally in Update, and the button isn't down, then the default value (0.0) will be used. It would be more clear what was going on if you wrote it like this:
 funtion Update () {
     var hpRayStall = 0.0;
     if(Input.GetButtonDown("P2hp"))
        {
          hpRayStall = Time.time + 1;
        }
 
              Your answer