Decrease 'Charge' of characters spotlight over time

var Charge = 100;

var LightOn = 1;

var LightOff = 0;

private var isLightOn = false;

function Update () {

if(Input.GetKeyDown(KeyCode.Q)) {
    isLightOn = !isLightOn;
}
    if(isLightOn == true) { 
            if(Charge > 0){
            light.intensity = LightOn;
                          }
}
    else{
        light.intensity = LightOff; 


        }
}

Ok so that is my script, at the moment I have a spotlight attached to my character and when I press 'Q' it toggles on and off. What I want is to make it have a power source that will run out after a set amount of time, two minutes for example.

As you can see I have set the charge of my spotlight to 100 and it turns on only if the charge is more than 0 however despite trying InvokeRepeating and yield functions to minus 1 from charge every x seconds I could not find a solution.

Any help you can give me to show me how to slowly decrease the charge would be much appreciated (I will also need to increase it again but i can probably work that out myself with a script for decreasing the charge)

Scribe

Let there be a max charge value such that Charge is between 0 and MaxCharge. Math.Lerp will give your light a gradient falloff between LightOff and LightOn.

light.intensity = Mathf.Lerp(LightOff, LightOn, Charge / MaxCharge);

Then you can simply reduce the charge such that:

Charge -= Time.deltaTime;

And you might want to make sure that the charge is in the correct interval:

Charge = Mathf.Clamp(Charge, 0, MaxCharge);

This give us functions we can use:

function DrainBattery()
{
    Charge = Mathf.Clamp(Charge - Time.deltaTime, 0, MaxCharge);
}

function UpdateLight()
{
    light.intensity = Mathf.Lerp(LightOff, LightOn, Charge / MaxCharge);
}

function CheckSwitch()
{
    if (Input.GetKeyDown(KeyCode.Q))
        light.enabled = !light.enabled;
}

And you can use them in your update like such:

function Update()
{
    CheckSwitch();
    if (light.enabled)
    {
        DrainBattery();
        UpdateLight();
    }
}

var Charge = 100;
var LightOn = 1;

var LightOff = 0;

private var isLightOn = false;

function Update () {
Charge -= 1 * Time.deltaTime;// you can change 1 to any number to drain the charge over a shorter amt of time.

if(Input.GetKeyDown(KeyCode.Q)) 
{
isLightOn = !isLightOn;
}
if(isLightOn == true)
{
         if(Charge > 0)
       {
        light.intensity = LightOn;
       } }    else{
    light.intensity = LightOff;         }
}

var Charge : float = 2;
var dischargeRate : float = 0.00666667;
var noCharge : float = 0;
@HideInInspector
var lightEnabled = false;

function Update()
{
	if (Input.GetKeyDown(KeyCode.Q))
	{
		lightEnabled = !lightEnabled;
	}
		
    if (lightEnabled == true && Charge > noCharge)
    {
       light.intensity = Charge -= (Time.deltaTime * dischargeRate);
	}
	
	else 
	{
		light.intensity = noCharge;
	}
}