AI Attack Cooldowns

What I am trying to do is to get it once it attacks, the value turns true and the attack is on cooldown which works, the attack won’t work while the value is true. The issue I am running into though seems to be when I do the cooldown, I am trying to keep it outside of the loop due to the fact that when it is in the loop the AI just stops until the cooldown is over but it just seems to not register if the value turns true at all outside of the loop.

Example of the code I am running (The changing of the value is within the attack functions):

while true do
	local nearestPlayer, distance, direction = locateTarget()
	if nearestPlayer then
		EnemyPosition = nearestPlayer.Character.HumanoidRootPart.Position
		if distance <= targetingDistance and distance >= stoppingDistance then
			RigHumanoid:Move(direction)
		else
			RigHumanoid:Move(Vector3.new())
		end
		if distance <= stoppingDistance then
			possessionFunction()
		end
		if distance >= stoppingDistance then
			primaryAttackFunction()
		end
	end
	wait(0.5)
end
--------------------------------------------------------
if primary == true then
	wait(10)
	primary = false
end

Change

if distance >= stoppingDistance then
	primaryAttackFunction()
end

to

if distance >= stoppingDistance and primaryCooldown == false then
	primaryCooldown = true
	
	primaryAttackFunction()

	wait(primaryCooldownLength)
	primaryCooldown = false
end

and also add the variables primaryCooldown = false and primaryCooldownLength = 10 with the rest of your variables.

If you don’t plan on changing the cooldown often or if your script isn’t that big, you can just do wait(10) instead.

1 Like

That is what I have tried but my main issue is it just ends up causing the AI to stop moving because it waits the primary cooldown, yet doesn’t do any other attacks because it has to wait until the cooldown is over before it can move, or do anything.

This should work then.

coroutine.wrap(function()
while wait(0.5) do
	local nearestPlayer, distance, direction = locateTarget()
			if distance <= targetingDistance and distance >= stoppingDistance then
			RigHumanoid:Move(direction)
		else
			RigHumanoid:Move(Vector3.new())
		end
		if distance <= stoppingDistance then
			possessionFunction()
		end
end
end)()


coroutine.wrap(function()
while wait(0.5) do
	local nearestPlayer, distance, direction = locateTarget()
	if nearestPlayer then
		EnemyPosition = nearestPlayer.Character.HumanoidRootPart.Position
		if distance >= stoppingDistance and primaryCooldown == false then
	primaryCooldown = true
	
	primaryAttackFunction()

	wait(primaryCooldownLength)
	primaryCooldown = false
end
	end
   end
end)()

That worked! Thank you so much.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.