When firing in a game, there can be a space of time between each shot.
fire, 1,2,3, fire, 1,2,3, fire…. and so on.
From the Scripting API:
Time.time
Description
The time at the beginning of this frame (Read Only).
This is the time in seconds since the start of the application…
//If the Fire1 button is pressed, a projectile
//will be Instantiated every 0.5 seconds.
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public GameObject projectile;
public float fireRate = 0.5f;
private float nextFire = 0.0f;
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(projectile, transform.position, transform.rotation);
}
}
}
Here is the order of precedence:
input.GetButton("Fire1") && ( Time.time > nextFire )
C# reference | Microsoft Learn
Operators and expressions — List all operators and expression —
Setup for first laser fire:
private float _canfire = -1f; // negative to okay firing starting out
if(Input.GetKeyDown(KeyCode.Space ) && ( Time.time > _canfire))
{
Instantiate(_laserPrefab, transform.position + _laserStart, Quaternion.identity);
}
Setup for each next laser fire:
[SerializeField]
private float _fireRate = 0.5f; // space between firing
private float _canfire = -1f; // negative to okay firing starting out
Logic for next laser fire:
0.5 > -1?
0.7 > 1.0?
0.9 > 1.0?
1.2 > 1.0?
1.4 > 1.7?
1.6 > 1.7?
1.8 > 1.7?
Here is the code:
if(Input.GetKeyDown(KeyCode.Space ) && ( Time.time > _canfire))
{
_canfire = Time.time + _fireRate;
Instantiate(_laserPrefab, transform.position + _laserStart, Quaternion.identity);
}