- Home /
How do you write a Pauseable-Timer Script in Unity JavaScript?
Hey Guys, I wondering how you would be able to make a Pauseable-Timer Unity.
I have a flashlight toggle script here:
 var flashlight : boolean;
 
 function Update () {
     if (Input.GetButtonDown("Fire2")) {
        GetComponent(Light).enabled = !GetComponent(Light).enabled;
     }
 
     if (GetComponent(Light).enabled)
     {
         flashlight = true;
         Debug.Log("Flashlight On");
     }else{
         flashlight = false;
         Debug.Log("Flashlight Off");
 
     }
 } 
I need to make a battery as a form as a GUIBox for the flashlight. At the start of the game, it would start at 100% and drop down to 0% in 1 second intervals. The player can switch off the flashlight which would pause the timer. (`Time.deltaTime`) I know I could use Time.deltaTime but I can't find a way to pause it. (P.S. I also need the player to find battery's scattered along an asylum or house which would increase their battery life in the flashlight.) 
Do this: if(flashlight){ timer += Time.deltaTime;} It will only add to the timer when the flashlight is on.
Answer by GTX Titan · Feb 01, 2014 at 01:48 PM
Do this:
 if(flashlight){
     if(timer < maxTimer)
         timer += Time.deltaTime;
 }
It will only add to the timer when the flashlight is on. This way you can then reset the timer like this: timer = 0; when a battery is picked or something. Also you would have to make the flashlight battery indicator work with the timer variable... for example:
 maxTimer = 120;
 indicator = (maxTimer - timer)/maxTimer*100;
 print(indicator + "%");
or something like that...
Im sorry, but i'm not sure how to code that as a whole. Sorry for me being such a n00b. And, if you want to, could you write a battery pickup script. If you don't want to don't. I don't even $$anonymous$$d if you don't write the script anyway. :-D Thank You
Well here's somewhat complete script:
 private var maxTimer:int;
 
 function Start(){
 
 maxTimer = 120; // time in seconds for the battery to reach 0% from 100%
 
 }
 
 function Update () {
 
 var indicator:float;
 
 if (Input.GetButtonDown("Fire2")) {
 
 GetComponent(Light).enabled = !GetComponent(Light).enabled;
 
 }
  
 if (GetComponent(Light).enabled)
 {
 
 flashlight = true;
 
 Debug.Log("Flashlight On");
 
 }else{
 
 flashlight = false;
 
 Debug.Log("Flashlight Off");
  
 }
 
 if(flashlight){
 
 if(timer < maxTimer)
 
 timer += Time.deltaTime;
 
 }
 indicator = (maxTimer - timer)/maxTimer*100;
 
 print(indicator + " %"); // this will show up on the bottom of unity left side
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                