Delay between bullet shot with GetKey
Hello, I'm trying to make a shooting game in which you can keep the W key pressed to shoot endlessly. The problem is that there is absolutely no delay between each bullet, so this looks more like a strange laser than a proper shoot. I tried to use WaitForSeconds but it couldn't work... I would like to know where I'm wrong. Help would be greatly appreciated. :) Here's my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerControl : MonoBehaviour {
public GameObject playerBulletGO; //bullet prefab
public GameObject bulletPosition01;
public GameObject bulletPosition02;
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKey("w") || Input.GetKey("z")) {
Shoot();
StartCoroutine(ShootWait());
}
float x = Input.GetAxisRaw ("Horizontal"); // will be -1 0 or 1 (for left, no input, and right)
float y = Input.GetAxisRaw ("Vertical"); // will be -1 0 or1 (for down, no input and up)
//now based on the input we comput a direction vector and we normalize it to get a unit vector
Vector2 direction = new Vector2 (x, y).normalized;
//now we call the function that computes and set the player's position
Move (direction);
}
void Move(Vector2 direction)
{ //here is the code for moving
}
void Shoot()
{
//instantiate the 1st bullet
GameObject bullet01 = (GameObject)Instantiate(playerBulletGO);
bullet01.transform.position = bulletPosition01.transform.position; //set the bullet initial position
//instantiate the 2nd bullet
GameObject bullet02 = (GameObject)Instantiate(playerBulletGO);
bullet02.transform.position = bulletPosition02.transform.position; //set the bullet initial position
}
IEnumerator ShootWait()
{
yield return new WaitForSeconds(100.0f);
}
}
Do you seriously believe you are the first one asking this question ? $$anonymous$$ake research please. Unity Answers is full of similar questions.
Answer by Sopqos · Jul 20, 2017 at 11:52 AM
public float fireRate = 2F; // 2seconds wait
private float nextFire = 0.0F;
.
if(Input.GetKey("w") || Input.GetKey("z") && Time.time > nextFire ) {
nextFire = Time.time + fireRate;
Shoot();
}
That should work (wont need startcourotine this way )
Invoke() is a better choice because he use a function when he clicked so : Invoke("Shoot", 2); should be better than your method.
Your answer
![](https://koobas.hobune.stream/wayback/20220612130700im_/https://answers.unity.com/themes/thub/images/avi.jpg)