Clear timer isn't working


I have found a problem when you want to stop a timer while it is being handled. I have the following situation.

When I press a button, my character starts to fire automatically at a target by using SetTimer(). When the target dies, it calls a method within my character that should stop the timer. However, that isn’t happening. I used the debugger to see what happens, and inside InternalClearTimer() the following code is executing:

// Edge case. We're currently handling this timer when it got cleared.  Unbind it to prevent it firing again
// in case it was scheduled to fire multiple times.
		if (CurrentlyExecutingTimer.TimerHandle == InHandle)

This make sense to me because the timer is executed, I fire at the target, the target dies and I want to cancel that timer, so this timer is still being handled. However the above piece of code should handle that case, or at least that’s what I think. Instead the timer keeps firing over and over again.

I don’t think so. Here’s the code that I have:

void ATPSWeapon::OnStartFire()
    GetWorldTimerManager().SetTimer(TimerHandle_ShootWeapon, this, &ATPSWeapon::OnStartFire, FireRate, false);

To be honest I wasn’t sure how automatic firing would work, so I checked the shooter game demo. They seemed to be doing the same thing but with some additional tricks like checking for ammo and the current state of the weapon.

Any chance you are creating multiple timers?

Try clearing that timer before you set it. If that works, OnStartFire is being called too often without cleanup.

Your solution worked! I also found that if I use a simple bool check before setting the timer, the problem doesn’t appear anymore.