timer

hey guys so i have made a fps game and i have a flashlight on one of the weapons. what id like to do is make a timer so that when you turn the flashlight on with (Shift + 2) it has 15 minutes before it turns off… also i would like to know how to keep it at the current time it would be at incase i turn it off with with (Shift + 2).

You could maybe Unity - Scripting API: WaitForSeconds

or you could keep a track of Unity - Scripting API: Time.time and update it as you see fit.

Personally I would go with WaitForSeconds().

I’d go with a ‘charge’ counter that you decrease during update by subtracting Time.deltaTime when the light is turned on. When it reaches Zero (or is <0), the Charge is depleted, and the light turns off. I find this helpful because

  • it’s near trivial to implement
  • automatically works with pausing the game and ‘bullet time’ (or all other effects that affect Time.timeScale)
  • you can simulate finding battereies that aren’t fully charged
  • using the Charge amount you can modify the lifgh’s intensity and color, simulating how Charge runs down and the light grows darker.
float timer = 0f;
public float timerInterval = 900f; // 15 * 60 = 900 seconds
bool isFlashlightOn = false;

void Start()
{

   timer = timerInterval; // reset flashlight to 15 mins charge 
}
void Update()
{
   if(isFlashlightOn && timer > 0)
   {
       timer -= Time.deltaTime;
      if(timer <= 0f)
      {
         isFlashlightOn = false;
         // turn off flashlight here as you ran out of charge
       }
   }
   else
   {
          isFlashlightOn = false;
         // turn off flashlight here as you ran out of charge
   }
}

Something like that, note that was written freehand without an IDE so may contain some issues but should get you on right path.

If you do it from a coroutine the gameobject will only take resources when the flashlight is on / recharging. One game object with a update is not a problem though.

1 Like