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:
public class Flashlight : MonoBehaviour
{
bool m_isOn;
public GameObject light;
float m_batteryTimer;
public float batteryDuration;
public void Flip()
{
if (m_isOn) TurnOff();
else TurnOn();
}
public void TurnOn()
{
if (m_batteryTimer < batteryDuration)
{
m_isOn = true;
light.SetActive(true);
}
}
public void TurnOff()
{
m_isOn = false;
light.SetActive(false);
}
void Start()
{
m_isOn = light.activeInHierarchy;
}
void Update()
{
if (m_isOn && m_batteryTimer < batteryDuration)
m_batteryTimer += Time.deltaTime;
if (Input.GetMouseButtonDown(0))
Flip();
}
}
Links you might find useful:
Time.deltaTime
GameObject.activeInHierarchy
Input.GetMouseButtonDown()