Function firing 1 more each time

I have the slapfunc() firing in a while loop that detects when the enemy is close and then fires the function. (It does this based off an if statement checking the magnitude, idk if this might be important) What happens each time the function fires however, is that the amount of times the player is hit increases each time he gets hit, so first 1 time, then 2, then 3 times etc. How do I fix this problem?

function slapfunc()
    if attack1cd == false then
        attack1cd = true
        slap:Play()
        slap.KeyframeReached:Connect(function(keyframe)

            if keyframe == "SlapFrame" then
                local hitbox = Instance.new("Part")
                hitbox.Size = Vector3.new(5, 5, 5)
                hitbox.CFrame = selfroot.CFrame:ToWorldSpace(CFrame.new(0, 0, -1.5))
                hitbox.Anchored = true
                hitbox.Parent = workspace
                hitbox.Material = Enum.Material.ForceField
                hitbox.CanTouch = false
                hitbox.CanCollide = false
                hitbox.CanQuery = false
                local canthitlist = {
                    
                }
                for _, part in workspace:GetPartsInPart(hitbox) do
                    if part:IsA("Part") and part ~= selfroot and part.Name == "HumanoidRootPart" and table.find(canthitlist, part) == nil then
                        table.insert(canthitlist, part)
                        part.Parent:FindFirstChildOfClass("Humanoid"):TakeDamage(10)
                        print("DMGED!")
                    end

                end
                task.delay(0.1, function()
                    hitbox:Destroy()
                end)
            end
        end)
        task.wait(0.7)
         attack1cd = false
        

    end

end

is what i mean:

image

see multiple happening at the exact same time:

every time you fire the slapfunc() function, it makes a new connection. So each time you slap, it makes a new event and triggers it.

You can fix this by disconnecting the function when its not needed any more.
replace it w this:

local conenection = slap.KeyframeReached:Connect(function(keyframe)

and add this:

task.wait(0.7)
attack1cd = false
connection:Disconnect()

let me know if your still having the issue.

1 Like

You could also use slap.KeyframeReached:Once which automatically disconnects the function once it is called

1 Like

exactly, forgot abt that, nice.

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