How could you calculate if a weapon can shoot using just Time.time and the weapon's fire rate?

I have a Weapon class with a TryShoot method. It checks the time and it’s fire rate and I want to calculate if it can shoot without storing a “lastTimeShot” variable. I’ve been fooling around with the % operator, but to no avail.

Pretty sure that would be impossible. It sounds like you are pinning yourself in the corner without good reason.
You can either use lastTimeShot, or nextAvailableTime = Time.time + fireRate;

How would you know if a shot was previously fired in too short a time to fire again if you’re only using the fire rate and Time.time?

I generally do something like this:

private float timeBetweenShots = 1f;
private float timeSinceLastShot = 0f;

update()
{
    timeSinceLastShot += Time.deltaTime;
    if (timeSinceLastShot >= timeBetweenShots)
    {
        if (checkIfWantingToShoot())
        {
            doShoot()
            timeSinceLastShot = 0f;
        }
    }
}

private bool checkIfWantingToShoot()
{
    //Do whatever you want here to check if you want to shoot, like check for button press or mouse click, or check if an AI wants to shoot - return true if you want to shoot, false if you don't
}

private void doShoot()
{
    //Bang!
}
1 Like

@Joe-Censored
You’re probably right @methos5k
The reason I’m not wanting to store the last or next time the weapon can shoot is because the weapon is a scriptable object (so I can have an array of them and easily create/cycle between them) and that variable would have to be reset in an OnApplicationQuit method (cuz scriptable objects don’t reset when leaving playmode) which seems messy, but if I gotta do it that’s fine.

*Edit: Damn, scriptable objects dont get an OnApplicationQuit callback
*Edit: I could check if lastTimeShot is greater than Time.time and if it is that means it hasn’t been reset yet. Then I can just set it to zero.

Well, I can relate in some ways (with SOs). I don’t use your method when I have similar situations, though.
What I’d do is have a container for the ScriptableObject. Then, for this simple example, I’d have ‘nextShotTime’ and the scriptable obj as variables. Let this ‘container’ class handle it.

I’d have a “state” class for the individual instance of the weapon, and then pass that to the “type” ScriptableObject class. Something like:

public class WeaponState
{
   public float lastShotTime;
   public int ammunition;
   // Other properties as needed.  
}
...
public interface IWeaponType  // Or abstract class BaseWeaponType : ScriptableObject
{
   void AttemptShot (ICreature firer, WeaponState state);
}