When my enemy manage instantiates the enemy, the enemy fires instantly instead of waiting for the fire rate. This only happens after the first spawned enemy. My guess is that since time.time is = to 0 at start it waits for the entire rate of fire but the next enemy that spawns time is already past.
if (Time.time > fireRate + lastShot)
{
SpawnProjectile();
lastShot = Time.time;
}
I am curious if i should do a waitforseconds? What do you guys recommend to do in this case. Other than the initial spawning shot rate of fire works fine.
Is this a script attached to each enemy or on a script that is separate from your enemy objects?
My suggestion would be in the script, set lastshot equal to Time.time in the start,awake, or onenable, just somewhere where it gets set before it starts running your check to see if it should fire or not. That way it will always be set to the current time when it spawns.
Or you can set this value in a method for when you spawn it. Either way should work out.
I do it like this.
public float FireRate;
public float NextFire;
void Awake()
{
NextFire = Time.time + FireRate;
}
void Update()
{
Fire();//try and shoot every frame
}
public void Fire()
{
if (Time.time > NextFire)
{
//do your bullet instantiation and ammo check here
NextFire = Time.time + FireRate;
}
}
Setting the variable to time.time worked great, awesome suggestion! Thanks.