- Home /
InvokeRepeating() not working.
I am trying to fire bullets at a rate determined by the weaponFireRate variable, but no matter what I do it will always fire one bullet per seconds. Here is the code:
public int health;
public int playerSize;
public int weaponDamage;
public float weaponFireRate = 10.0f;
public int bulletSpeed = 10;
public int bulletSize;
public GameObject bullet;
private bool shooting = false;
// Use this for initialization
void Start () {
InvokeRepeating("Shoot", 0.0f, (1.0f / weaponFireRate));
}
// Update is called once per frame
void Update () {
shooting = false;
if (Input.GetButton("Fire1"))
{
Shoot();
shooting = true;
}
}
void Shoot()
{
if (!shooting) return;
GameObject bulletClone;
bulletClone = Instantiate(bullet, transform.position, transform.rotation);
bulletClone.GetComponent<Rigidbody2D>().AddForce(bulletClone.transform.up * bulletSpeed);
}
Any help would be greatly appreciated!
Could the issue be co$$anonymous$$g from somewhere else?
While you won't be able to change the fire rate at runtime, you should expect 10 bullets per second. Unless you have "1" set as the weaponFireRate in the editor.
If you're already assigning the value of weaponFireRate, you shouldn't make it public. You could be unintentionally changing it from somewhere else? . Try putting Logs to see what value weaponFireRate actually have when you feed it into Invoke Function.
Answer by suerozcelik · Aug 10, 2017 at 06:19 PM
public int health; public int playerSize; public int weaponDamage; public float weaponFireRate = 10.0f; public int bulletSpeed = 10; public int bulletSize; public GameObject bullet; private bool shooting = false; InvokeRepeating("Shoot", 0.0f, (1.0f / weaponFireRate)); // Use this for initialization void Start () {
}
// Update is called once per frame void Update () { shooting = false; if (Input.GetButton("Fire1")) { Shoot(); shooting = true; } } void Shoot() { if (!shooting) return; GameObject bulletClone; bulletClone = Instantiate(bullet, transform.position, transform.rotation); bulletClone.GetComponent().AddForce(bulletClone.transform.up * bulletSpeed);
} Don't use at start function.
Your answer
![](https://koobas.hobune.stream/wayback/20220612105257im_/https://answers.unity.com/themes/thub/images/avi.jpg)