# Stop shooting infinite bullets with touch

Hey guys, I am trying to adapt my touch script. Touch is my weakest point I believe.

Here I have this code…

``````void Update ()
{
Touch touch;

if(Input.touchCount > 0 )
{
touch = Input.touches[0];
if(targetTex.HitTest(touch.position))
{
if (touch.phase == TouchPhase.Began)
targetTex.texture = touchTex;

if(moveCtrl.facingRight)
{
// ... instantiate the BulletPrefab facing right and set it's velocity to the right.
Rigidbody2D bulletObject = Instantiate(BulletPrefab, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
bulletObject.velocity = new Vector2(speed, 0);
}
else
{
// Otherwise instantiate the BulletPrefab facing left and set it's velocity to the left.
Rigidbody2D bulletObject = Instantiate(BulletPrefab, transform.position, Quaternion.Euler(new Vector3(0,0,180f))) as Rigidbody2D;
bulletObject.velocity = new Vector2(-speed, 0);
}
}
}
``````

This shoots so many bullets as long as my finger is down. I want it that when I tap it, the bullet fires once and onces only… How can I do this? Im sure its the way I have set the touch stuff but I can’t seem to figure it out.

Set a boolean to true at TouchPhase.Began and to false at TouchPhase.Ended, and and use it to fire only once (when it’s false).

I wrote a little example code for you to look at. Whether you will use it or not is up to you. You will need to integrate it with your own script ,but basically this script fires a bullet at a specified fire rate. Best of luck on your project

``````public class ShootBullets : MonoBehaviour
{
// Bullets per second
public float fireRate = 5f;

float fireTimer;

void Start () {
fireTimer = Time.time;
}

void Update ()
{
// Check for touch input as well as mouse input -
// so we can test in the editor
if (Input.touchCount > 0 || Input.GetMouseButton(0)) {
if (Time.time >= 1/fireRate + fireTimer) {
// Set the time at which the last bullet was fired
fireTimer = Time.time;

// Do whatever you do to spawn your bullets here
Debug.Log ("Firing a bullet!");
}
}
}
}
``````

I had a variation of this problem when implementing a toggle button. When the button was down it would switch between states very rapidly.

Basically, I just implemented an extra boolean variable so that an action would only happen once…

``````var toggle : boolean = true;

if (touch.phase == TouchPhase.Began){
if(toggle == true){
//fire bullet
}
//after it fires the first bullet it sets toggle to false to it won't fire again
toggle = false;
}

if (touch.phase == TouchPhase.Ended){
toggle = true;
}
``````