- Home /
How to increase a variable over time while button is held in C#?
The end result I am trying to achieve is to have a weapon charge up by holding a button down, similar to R-type. I have seen references to this on here in JavaScript, but I am working in C#. I am trying ti use Time.deltaTime but what I have right now reaches my limit instantly, and if I adjust the speed too low or the limit too high, it crashes the program.
//Charges Projectile.
if (Input.GetButtonDown("ForwardFire"))
{
while(Input.GetButton("ForwardFire") && chargeLevel < chargeLimit)
chargeLevel += Time.deltaTime * chargeSpeed;
}
//Fires projectile.
if (Input.GetButtonUp("ForwardFire"))
{
Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletOffset);
Instantiate(forwardProjectile, position, Quaternion.identity);
chargeLevel = 0;
}
Oh, and please use little words because if you haven't figured it out already, I don't really know what I'm doing here.
Answer by amphoterik · Jul 26, 2013 at 03:24 PM
You are close. Avoid the loop:
//Charges Projectile.
if (Input.GetButtonDown("ForwardFire") && chargeLevel < chargeLimit))
{
chargeLevel += Time.deltaTime * chargeSpeed;
}
//Fires projectile.
if (Input.GetButtonUp("ForwardFire"))
{
Vector3 position = new Vector3(transform.position.x, transform.position.y + bulletOffset);
Instantiate(forwardProjectile, position, Quaternion.identity);
chargeLevel = 0;
}
Though its worth noting that you never use your charge level except for timing purposes (I assume you are using it elsewhere)
You are my new best friend-works great! I need to start co$$anonymous$$g here first ins$$anonymous$$d spending all morning trying to figure things out on my own.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Value * deltatime / deltatime ? 1 Answer
Time.deltaTime making color lerp appear fast, but won't reach 1 1 Answer