Hi there - Unity noob here. So in the Indie horror game I’m working on, I have a flashlight attached to my player. So far, I have scripted the flashlight to activate and deactivate with ‘E’, and it has a cooldown of 10 seconds before you can activate it again. However, before scripting the cooldown, my flashlight had a ‘limit’ where it would last for 30 seconds and then turn off. However, after adding my cooldown code, the limit is not working and the light stays on forever unless I press ‘E’. Can somebody point me in the right direction? Thanks.
Here’s my code:
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
public class FlashlightCooldown : MonoBehaviour
{
public float battery = 30;
// Start is called before the first frame update
void Start()
{
//Light is automatically off on initialise
GetComponent<Light>().enabled = false;
}
// Update is called once per frame
public float FlashlightCoolDown = 10f;
private bool FlashlightOnCooldown;
void Update()
{
//If flashlight is not on cooldown, use flashlight when 'E' is pressed
if (!FlashlightOnCooldown && Input.GetKey(KeyCode.E))
{
StartCoroutine(UseFlashlight());
}
}
IEnumerator UseFlashlight()
{
FlashlightOnCooldown = true;
battery = battery - Time.deltaTime;
//If the battery is more than 0, it can be activated with 'E'
if (Input.GetKeyDown(KeyCode.E))
{
if (GetComponent<Light>().enabled == false)
{
if (battery > 0)
{
GetComponent<Light>().enabled = true;
}
}
else
//Light is not activated
{
GetComponent<Light>().enabled = false;
}
}
//If battery is 0, do not activate light when 'E' is pressed
if (battery < 0)
{
battery = 0;
GetComponent<Light>().enabled = false;
}
yield return new WaitForSeconds(FlashlightCoolDown);
FlashlightOnCooldown = false;
}
}