Search Unity

how to make a flashlight battery system

Discussion in 'Scripting' started by rezwa, May 9, 2021.

  1. rezwa

    rezwa

    Joined:
    Apr 26, 2021
    Posts:
    12
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Lightcrip : MonoBehaviour
    {
    public Animator anim;
    public GameObject Light;
    public bool LightActive;
    public AudioSource clickSound;

    void Start()
    {
    Light.SetActive(false);
    anim = GetComponent<Animator>();
    anim.SetBool("ison", false);
    clickSound.Stop();
    }


    void Update()
    {
    if (Input.GetButtonDown("Fire2"))
    {
    LightActive = !LightActive;
    clickSound.Play();

    if (LightActive)
    {
    FlashLightActive();
    anim.SetBool("ison", true);
    }

    if (!LightActive)
    {
    FlashLightInActive();
    anim.SetBool("ison", false);
    }
    }
    }

    void FlashLightActive()
    {
    Light.SetActive(true);
    }

    void FlashLightInActive()
    {
    Light.SetActive(false);
    }
    }

    thats all my code for my flashlight i want to make it so when i click lmb (Fire2) a timer starts and keeps going down until i turn my flashlight off then i want the timer to pause and if the timer runs out you cant turn on the flashlight, im pretty new to coding and i tried my best to figure it out myself and what tutorials but none really helped so can someone please help me?
     
  2. chubshobe

    chubshobe

    Joined:
    Jun 20, 2015
    Posts:
    52
    Please read the code tags post.

    You can do this by using a simple timer which will count up while the flashlight is on. Example:
    Code (CSharp):
    1. public class Flashlight : MonoBehaviour
    2. {
    3.     bool m_isOn;
    4.     public GameObject light;
    5.     float m_batteryTimer;
    6.     public float batteryDuration;
    7.  
    8.     public void Flip()
    9.     {
    10.         if (m_isOn) TurnOff();
    11.         else TurnOn();
    12.     }
    13.  
    14.     public void TurnOn()
    15.     {
    16.         if (m_batteryTimer < batteryDuration)
    17.         {
    18.             m_isOn = true;
    19.             light.SetActive(true);
    20.         }
    21.     }
    22.  
    23.     public void TurnOff()
    24.     {
    25.         m_isOn = false;
    26.         light.SetActive(false);
    27.     }
    28.  
    29.     void Start()
    30.     {
    31.         m_isOn = light.activeInHierarchy;
    32.     }
    33.  
    34.     void Update()
    35.     {
    36.         if (m_isOn && m_batteryTimer < batteryDuration)
    37.             m_batteryTimer += Time.deltaTime;
    38.  
    39.         if (Input.GetMouseButtonDown(0))
    40.             Flip();
    41.     }
    42. }
    Links you might find useful:
    Time.deltaTime
    GameObject.activeInHierarchy
    Input.GetMouseButtonDown()