Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

The CanDoDamage variable is not providing a cooldown. How can I fix this script?

I am trying to make a script where pressing F would headbutt an enemy and damages them. The problem, however, is that after pressing F once, you no longer need to press F again to damage them, you just need to walk close to them.

local CanDoDamage = false
local UserInputService = game:GetService("UserInputService")
local Damage = 15

local Player = game.Players.LocalPlayer

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.F then
		local Animation = script.Parent.Humanoid:LoadAnimation(script.Animation)
		Animation:Play()
		script.Parent.Head.Touched:Connect(function(hit)
			if hit.Parent:FindFirstChild("Humanoid") and CanDoDamage == false then
				CanDoDamage = true
				hit.Parent:FindFirstChild("Humanoid"):TakeDamage(Damage)
				print("You attacked!")
				wait(1)
				CanDoDamage = false
			end
		end)
	end
end)

I tried adding the CanDoDamage variable to prevent this, but it still doesn't seem to work. How can I fix this? Also, this script isn't meant to work in multiplayer as there is no remote event or function.

1 comment

0

just use wait()

1 answer

✓ Accepted answer

You're connecting a new .Touched event every time you hit your F key. This isn't ideal, since this will create tons of connections and run the function here multiple times.

You should place the event outside of the InputBegan so you don't have multiple, as well as track the cooldown in there.

You may also need another debounce for the .Touched since you don't want it hitting multiple times in 1 second.

local CanDoDamage = false
local UserInputService = game:GetService("UserInputService")
local Damage = 15

local Player = game.Players.LocalPlayer

UserInputService.InputBegan:Connect(function(input)
    -- "not" just checks if the value is false instead of truthy
    if input.KeyCode == Enum.KeyCode.F and not CanDoDamage then
        local Animation = script.Parent.Humanoid:LoadAnimation(script.Animation)
        Animation:Play()
        CanDoDamage = true
        wait(1)
        CanDoDamage = false
    end
end)

script.Parent.Head.Touched:Connect(function(hit)
        if hit.Parent:FindFirstChild("Humanoid") and CanDoDamage == false then
            
            hit.Parent:FindFirstChild("Humanoid"):TakeDamage(Damage)
            print("You attacked!")
            
        end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.