Search Unity

timer

Discussion in 'Scripting' started by brayT, Aug 4, 2019.

  1. brayT

    brayT

    Joined:
    Jan 21, 2018
    Posts:
    65
    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).
     
  2. ismaelflorit

    ismaelflorit

    Joined:
    Apr 16, 2019
    Posts:
    38
  3. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    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.
     
  4. MadeFromPolygons

    MadeFromPolygons

    Joined:
    Oct 5, 2013
    Posts:
    3,982
    Code (CSharp):
    1.  
    2. float timer = 0f;
    3. public float timerInterval = 900f; // 15 * 60 = 900 seconds
    4. bool isFlashlightOn = false;
    5.  
    6. void Start()
    7. {
    8.  
    9.    timer = timerInterval; // reset flashlight to 15 mins charge
    10. }
    11. void Update()
    12. {
    13.    if(isFlashlightOn && timer > 0)
    14.    {
    15.        timer -= Time.deltaTime;
    16.       if(timer <= 0f)
    17.       {
    18.          isFlashlightOn = false;
    19.          // turn off flashlight here as you ran out of charge
    20.        }
    21.    }
    22.    else
    23.    {
    24.           isFlashlightOn = false;
    25.          // turn off flashlight here as you ran out of charge
    26.    }
    27. }
    Something like that, note that was written freehand without an IDE so may contain some issues but should get you on right path.
     
  5. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    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.
     
    ismaelflorit likes this.