Decrease a value over time when W is pressed.

Hey, what I am trying to achieve is this:

When the user presses the W key, I want the fuel variable to deduct by 10 every 5 seconds. I have written a little script but unfortunately for me, I’m only learning at the moment and can’t seem to suss it out :stuck_out_tongue: Here is my script:

var speed : float = 3.0;
var rotateSpeed : float = 3.0;
var bulletPrefab:Transform;
var shotDelay = 2;
var status1 = "Loaded";
var style : GUIStyle;
var fuel : float = 100.0;
var fuelDeduct = 2.0;

   function Start () {

    while (true) {
        while (!Input.GetButtonDown("Jump")) yield;
		bullet = Instantiate(bulletPrefab, GameObject.Find("SpawnPoint").transform.position, transform.rotation);
			bullet.tag = "bulletShot";
			status1 = "Reloading";
			bullet.rigidbody.AddForce(transform.forward * 5000);
        yield WaitForSeconds(shotDelay);
        status1 = "Loaded";
    }
}

function Update ()
{
	var controller : CharacterController = GetComponent(CharacterController);
	transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
	var forward : Vector3 = transform.TransformDirection(Vector3.forward); var curSpeed : float = speed * Input.GetAxis ("Vertical");
	controller.SimpleMove(forward * curSpeed);
	

	}
@script RequireComponent(CharacterController)

    if(Input.GetKey("w"))
    {
        fuel -= fuelDeduct * Time.deltaTime;
    }



function OnGUI()
{
		
    	GUI.Label(Rect(250, 70, 100, 20), status1, style);
    	GUI.Label(Rect(250, 120, 100, 20), fuel.ToString("f0"), style);
}  

Basically I wish for the fuel variable to deduct by 5 every 10 seconds but so far nothing is happening. Can anyone point me in the right direction? :slight_smile: Try not to spoon feed me please, I like learning the hard way :slight_smile:

Try something like this:

var style : GUIStyle;
var fuel : float = 100.0;
var fuelDeduct = 2.0;  // reduce 2 each second == 10 every 5 sec

function Update ()
{
    if(Input.GetKey("w"))
    {
        fuel -= fuelDeduct * Time.deltaTime;
    }
}

function OnGUI()
{     
    GUI.Label(Rect(250, 120, 100, 20), fuel.ToString("f0"), style);
}

This will continously reduce the fuel while the button is held down. This is way better than reducing it in big intervals.

Is one of the rewrites a removal of a loop in Start()? Because otherwise it’s never going to check for getkeyDown after the first check.

Keep in mind that the loop must reach a yield statement even if the player doesn’t hit a key.