using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunTimingExample : MonoBehaviour { public int magazineCapacity = 30; public int ammo = 30; public int roundsPerMinute = 800; public float reloadDuration = 1; float lastShotTime = 0; bool reloading = false; float timeSinceLastShot { get { //return how long since the last shot was fired return Time.time - lastShotTime; } } float shotInterval { get { //convert to seconds per round return 1f / (roundsPerMinute / 60f); } } private void Update() { if (Input.GetMouseButton(0)) { Fire(); } if (Input.GetKeyDown(KeyCode.R)) { Reload(); } } void Reload() { //dont allow reloading while reloading if (reloading) return; reloading = true; //call Reloaded after a period of time Invoke("Reloaded", reloadDuration); Debug.Log("Reloading... " + Time.time); } void Reloaded() { //include an extra round if gun was still chambered when reload began ammo = magazineCapacity + (ammo > 0 ? 1 : 0); reloading = false; Debug.Log("Reloaded! " + Time.time); } void Fire() { if (ammo > 0 && !reloading) { //use properties for legibility to make sure we're good to fire if (timeSinceLastShot >= shotInterval) { //decrement ammo ammo--; Debug.Log($"Bang! Ammo:{ammo} Delta:{timeSinceLastShot}"); //log the time the shot happened lastShotTime = Time.time; } } } }