Continuous tool action

So, I want a tool to continously hit while the mouse button is clicked down. Instead the tool only hits once per mouse click. I think I would need to add a while loop , but I don’t know where the while loop would go. If there is another option it would be great if you would let me know! The code below is scripted into the tool which is inside the starter pack.

local CS = game:GetService("CollectionService")
local tool = script.Parent
local canDamage = false
local canSwing = true

local function onTouch(otherPart)

    local humanoid = otherPart.Parent:FindFirstChild("Humanoid")

    if not humanoid then 
        return 
    end

    if humanoid.Parent ~= tool.Parent and canDamage and CS:HasTag(humanoid,"Rock") then
        humanoid:TakeDamage(18)
        print("Slashed")
    else
        return
    end

    canDamage = false
end

local function slash()
    if canSwing then
        canSwing = false
        local str = Instance.new("StringValue")
        str.Name = "toolanim"
        str.Value = "Slash" 
        str.Parent = tool
        canDamage = true
        wait(0.8)
        canSwing = true
    end
end

tool.Activated:Connect(slash)
tool.Handle.Touched:Connect(onTouch)
1 Like

I think you have the right idea with the while loop I think you should do something like this

local function slash()
while canSwing do
        canSwing = false
        local str = Instance.new("StringValue")
        str.Name = "toolanim"
        str.Value = "Slash" 
        str.Parent = tool
        canDamage = true
        wait(0.8)
        canSwing = true
    end
end

I suggest you have a look at UserInputService:IsMouseButtonDown()
And you can do a while loop with the conditions of if the mouse button is down and if the tool is equipped.