Shoot = Input.GetKey(KeyCode.Z);
if (Shoot)
{
Shoot = true;
foreach(Gun gun in guns)
{
gun.Shoot();
}
}
Gun:
public void Shoot()
{
GameObject go = Instantiate(bullet.gameObject, transform.position, Quaternion.identity);
Bullet goBullet = go.GetComponent<Bullet>();
goBullet.direction = direction;
}
This creates a bullet every frame when I hold Z and I don’t want that. How can I control the instantiation rate?
I followed this guide here when making this but it doesn’t get adressed.
You could try adding a timer between each shot by making a ShotTime and ShotTimer float, decreasing the shotTimer by time.deltaTime each frame and only doing the shoot function when ShotTimer is below or equal to zero. then just reset ShotTimer to ShotTime every time you shoot. I dont know if this makes any sense whatsoever but hopefully it helps.
// The current time until the next bullet is fired
private float currentShootCooldown;
// The time between two shots
private float maxShootCooldown;
void Start()
{
maxShootCooldown = .1f; // For a cooldown of 0.1 seconds
}
void Update()
{
if (currentShootCooldown > 0f)
{
currentShootCooldown -= Time.deltaTime;
}
// You can either use GetKey for shooting every cooldown interval while holding or
// GetKeyDown for shooting every time you press the button down (holding doesn't work)
else if (Input.GetKey(/* Whatever button you want to shoot with */))
{
Shoot();
currentShootCooldown = maxShootCooldown;
}
}
void Shoot()
{
// Shoot your bullet here
}