So I'm new to Unity and been following a lot of Brackey's tutorials to find my way. I want to make some sort of FPS game so I watched "Shooting with Raycasts - Unity Tutorial" It all works until I add the fire rate in and then it just seems to not work. When I use the code below, the gun shoots full auto since it is "GetButton" but the fire rate doesn't seem to come into play at all. Can anyone help? Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunScript : MonoBehaviour { public float damage = 25f; public float range = 100f; public AudioSource gunShot; public float fireRate = 1f; public Camera fpsCam; public ParticleSystem muzzleFlash; private float nextTimeToFire = 0f; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if(Input.GetButton("Fire1") && Time.time >= nextTimeToFire) { nextTimeToFire = Time.time + 1f / fireRate; Shoot(); } } void Shoot() { muzzleFlash.Play(); gunShot.Play(); RaycastHit hit; if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range)) { Debug.Log(hit.transform.name); Enemy target = hit.transform.GetComponent<Enemy>(); if(target != null) { target.TakeDamage(damage); } } } }
This is commonly called a "cooldown timer." You can google for examples and tutorials, but the simplest way is this: 1. have a private float gunHeat; variable 2. In Update(), if that variable is greater than zero, subtract Time.deltaTime from it (this cools down the gunHeat) Code (csharp): if (gunHeat > 0) { gunHeat -= Time.deltaTime; } 3. When you go to fire: --- A. only fire if that gunHeat variable is zero or less. --- B. set that variable to the time (in seconds) you want to have between shots. Code (csharp): if (UserWantsToFireTheGun) { if (gunHeat <= 0) { gunHeat = 0.25f; // this is the interval between firing. ActuallyDoTheFiring(); } }
Seriously thanks. Been trying this many ways and when looking at this way I feel like an idiot. Thanks