1

I am making shooting in Unity, what I want is to make a little delay, for example: to be able to shoot in every 0.5 seconds. Check the script, I want my bullet prefab to appear (instantiate) after 0.5 sec delay.

private Rigidbody2D rb2d;
private float h = 0.0f;
public float Speed;
public Transform firePoint;
public GameObject bulletPrefab;


    // Start is called before the first frame update
void Start()
{
    rb2d = GetComponent<Rigidbody2D>();

}

// Update is called once per frame
void Update()
{
    h = Input.GetAxisRaw("Horizontal");
    if (h != 0.0f)
    {
        rb2d.velocity = new Vector2(h * Speed, rb2d.velocity.y);
    }
    if (h == 0.0f)
    {
        rb2d.velocity = new Vector2(0, rb2d.velocity.y);

    }

    if (Input.GetKeyDown(KeyCode.Space))
    {
        Shoot();
    }
}


void Shoot()
{
    Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
  • 2
    Possible duplicate of [How make the script wait/sleep in a simple way in unity](https://stackoverflow.com/questions/30056471/how-make-the-script-wait-sleep-in-a-simple-way-in-unity) – Eliasar May 08 '19 at 17:06

1 Answers1

2

This should take you in the right direction, of course, this is only one of the ways to do it.

You can change fireDelay to change the rate of fire.

private Rigidbody2D rb2d;
private float h = 0.0f;
public float Speed;
public Transform firePoint;
public GameObject bulletPrefab;

float fireElapsedTime = 0;
public float fireDelay = 0.2f;


    // Start is called before the first frame update
void Start()
{
    rb2d = GetComponent<Rigidbody2D>();

}

// Update is called once per frame
void Update()
{
    h = Input.GetAxisRaw("Horizontal");
    if (h != 0.0f)
    {
        rb2d.velocity = new Vector2(h * Speed, rb2d.velocity.y);
    }
    if (h == 0.0f)
    {
        rb2d.velocity = new Vector2(0, rb2d.velocity.y);

    }

    fireElapsedTime += Time.deltaTime;

    if (Input.GetKeyDown(KeyCode.Space) && fireElapsedTime >= fireDelay)
    {
        fireElapsedTime = 0;
        Shoot();
    }
}


void Shoot()
{
    Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
parveen
  • 1,939
  • 1
  • 17
  • 33
  • Thanks, that's works fine. Can you give me a little explanation what fireElapsedTime and fireDelay variables do? I'm new to both Unity and programming. –  May 08 '19 at 19:01
  • Sure @jolskey , `fireElapsedTime` tracks how much time has passed since the player last fired, `fireDelay` is the amount of time before the player can fire again. By increasing/decreasing the delay you can decrease/increase fire rate respectively. – parveen May 09 '19 at 09:50