Shooting a projectile the longer a button is held c#

I’m trying to shoot a projectile the longer the mouse is held down. To do this I am incrementing a variable in void update. I seemingly have two problems. 1. The variable is not properly increasing, and 2. nothing is happening when GetButtonUp should be called. Here is my code so far:

EDIT: I fixed problem 2. I was calling the buttonUp on “Fire2” not “Fire1.” The first problem still persist.

GameObject prefab;

// Use this for initialization
void Start () {
	prefab = Resources.Load ("Projectile") as GameObject;

}

// Update is called once per frame
void Update () {

	int x = 0;

	if (Input.GetButton ("Fire1")) {

		//Debug.Log ("Mouse 1 down");

		x += 1;

		Debug.Log (x);

		//if (x < 99) 
			//x = 100;

		if (Input.GetButtonUp ("Fire2")) {
			Debug.Log ("Mouse 1 up");
			GameObject Projectile = Instantiate (prefab, transform.position, transform.rotation)                      as GameObject;
			Projectile.transform.position = transform.position + Camera.main.transform.forward   * 2;
			Rigidbody rb = Projectile.GetComponent<Rigidbody> ();
			rb.velocity = Camera.main.transform.forward * (x / 4);

		}		
	}
}
}

You have 3 problems here:

  • You use an int variable where you should use a float variable that represents the “time passed” instead of frames passed.
  • You declared your variable inside Update. That means it will loose it’s content after Update is completed. Since it should hold it’s value over multiple frames you have to declare it outside of Update as a class member variable.
  • GetButtonUp will only return true for one frame when the button is released. Since you have the check inside the other if that will never happen. If the button was released this frame then GetButton will return false so you don’t enter the outer if anymore.

So it should look like that:

public float minForce = 0.2f;
public float maxForce = 2f;
public float chargeSpeed = 1f;
float x = 0f;

void Update ()
{ 
    if (Input.GetButton ("Fire1"))
    {
        x += Time.deltaTime * chargeSpeed; // increase x by "chargeSpeed" per second
    }
    if (Input.GetButtonUp ("Fire1"))
    {
        GameObject Projectile = Instantiate (prefab, transform.position, transform.rotation)                      as GameObject;
        Projectile.transform.position = transform.position + Camera.main.transform.forward   * 2;
        Rigidbody rb = Projectile.GetComponent<Rigidbody> ();
        x = Mathf.Clamp(x, minForce, maxForce);
        rb.velocity = Camera.main.transform.forward * x;
        x = 0f;
    }        
}

minForce allows you to specify a minimum force that is used if the user only “clicks”.

maxForce limits the force you can reach.

chargeSpeed controls how fast your variable charges.

Once the projectile is launched it’s important to set x back to 0 for the next one.