TakeDamage scripts damages even after character stops touching part roblox

So I made a part that deals damage over time but I want it so that the part stops doing damage when not touched. I tried using TouchEnded but that did not work at all.

local debounce = false

script.Parent.Touched:Connect(function(hit)
	while debounce == false do
		if hit.Parent:FindFirstChild("Humanoid") then
			debounce = true
			hit.Parent.Humanoid:TakeDamage(10)
			wait(1)
			debounce = false
		end 
	end
end)
  local debounce = false

script.Parent.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Humanoid")  and debounce == false then
			debounce = true
			hit.Parent.Humanoid:TakeDamage(10)
			wait(1)
			debounce = false
		end
end)

Maybe try this instead, It might work
Edit: It works for me

1 Like

I already tried that, the same outcome. It will keep damaging when I stop touching the part.

if you do while debounce == false do, the script will see that as a while true do loop (false == false means true), and it would coutinue to take damage from you even though you are not touching it.

It is because you set debounce to false when the loop ends, and it keeps running, so you don’t even have to be touching it

Oh, so if I remove that and then I add a touch ended line with debounce = false that might work…

You can store it in a table.

local hitPlayers = {}
script.Parent.Touched:Connect(function(hit)
    local hum = hit.Parent:FindFirstChild("Humanoid")
    if hum and not table.find(hitPlayers, hum) then
        table.insert(hitPlayers, hum)
        while table.find(hitPlayers, hum) do
            hum:TakeDamage(10)
            wait(1)
        end
    end
end)
script.Parent.TouchEnded:Connect(function(hit)
    local hum = hit.Parent:FindFirstChild("Humanoid")
    if hum and table.find(hitPlayers, hum) then
        table.remove(hitPlayers, table.find(hitPlayers, hum))
    end
end)

didn’t work, i tried making it print something when it touched but It didn’t print that.

Actually, I think that works, I tried it on another part and it worked but sometimes it went too fast but that’s fine I can try to fix that, but for some reason it wont work with my other part

Yeah, you might need to add some leniency check because maybe the left leg touches and the right one also does, then the left leg fires touchended

Oh wait, I think your script only damages when you touch the part and when you stop touching it, I stood at the edge of the part and it continuously damaged me, but when I stood in the middle, it only damaged me once.

Figured it out, I can make a transparent, non-collidable, brick inside and use:

while true do
	wait()
	script.Parent.Position = script.Parent.Position + Vector3.new(0, 1000, 0)
	wait()
	script.Parent.Position = script.Parent.Position - Vector3.new(0, 1000, 0)
end