I am currently creating an FPS game, and I am stuck with this issue.
Basically when I hold the left click button, a variable called “currentAmmo” is being decremented fast rather than constantly. The audio is being “spammed” as well.
What is happening when I press left click: (30, 23, 18, 5… etc). Numbers are random, as this is just an example.
What it should be: (30, 29, 28…)
Below, kindly find the code.
public void shoot()
{
//left click
if (Input.GetMouseButton(0))
{
if (aimsight)
{
animator.Play("ak47shootSight");
audioSource.PlayOneShot(ak47Shoot);
}
currentAmmo--;
Debug.Log(currentAmmo);
if (!aimsight)
{
animator.Play("ak47Shooting");
audioSource.PlayOneShot(ak47Shoot);
}
}
}
Thanks a lot for your help and I apologize for my newbie question.
If this code is being called every frame then yes - that is going to mean bullets are going be firing like crazy!
Your best bet is to use a timer to reduce the firing rate. Not only will this provide a more constant rate of fire, but it will give you flexibility to have different firing rates for different weapons (eg a sub machine may fire faster).
The only thing I would add to matthewseaward’s solution is to make sure that there is just one instance of shoot() happening in the scene i.e there is only one gameobject placed in the scene with shoot() called in it’s update.