Hey guys, so I thought I had control over my fire rate in my script, although it would appear I don’t and my gun always shoots at the same rate.
I’d greatly appreciate it if someone could explain to me what I am doing wrong here and how I can get control over my fire rate? Below i’ll drop my Gun script.
Thanks again for any help!
using UnityEngine;
public class Carbine : MonoBehaviour
{
public int minimumDamage = 5;
public int maximumDamage = 15;
public int maximumRange = 50;
public float fireRate = .05f;
private float nextFire = 0f;
public ParticleSystem MuzzleFlash;
public Camera MainCamera;
public GameObject ImpactEffect;
void FixedUpdate ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
Shoot();
}
}
void Shoot ()
{
MuzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(MainCamera.transform.position, MainCamera.transform.forward, out hit, Mathf.Infinity))
{
Instantiate(ImpactEffect, hit.point, Quaternion.LookRotation(hit.normal));
GameObject go = Instantiate<GameObject>(ImpactEffect, hit.point, Quaternion.LookRotation(hit.normal));
IDamageable damageable = hit.collider.GetComponent<IDamageable>();
if (damageable != null)
{
float normalisedDistance = hit.distance / maximumRange;
if (normalisedDistance <= 1)
{
damageable.DealDamage(Mathf.RoundToInt(Mathf.Lerp(maximumDamage, minimumDamage, normalisedDistance)));
nextFire = Time.time + fireRate;
}
}
}
}
}
What’s exactly is the issue, is it too fast, too slow?
From glancing over your code, it does seem a little odd to me that you would only reset the nextFire variable, when you hit something damageable. So, if you hit a wall, or something indestructible, nextFire won’t update.
Also; something else to mention is that you’re using FixedUpdate(), and that runs every Physics Frame(not necessarily every single frame, it’s almost every frame, which may give some unexpected results). You should probably check for player input(ie: Input.GetButton) in the Update() function.
Yeah, no problem, man. I’ll tell you what I know, I’m not an expert by any means though.
So there’s an Update() function, you know? All the code in the Update() function gets called every single frame. FixedUpdate() is a special function that should only be used when using code that references the rigidbody, or uses physics. This is not called every frame. Reference the doc for a little more info https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
That said, it’s highly recommended that you check for player input every frame by using the Update() function.
Otherwise, it could be seen as unresponsive.
Does that make a little more sense, maybe? I hope the other advice helps you.
As a sidenote(towards your other post), setting nextFire on Line 32 would work.