I'm making an ocean floor where if you touch it, it slowly does damage until you stop touching it. The TouchConnected works fine, but when the player leaves it (TouchEnded), it occasionally fails to detect it, but also sometimes work (too inconsistent). What did I do wrong?
Here's the script to detect the player:
local CollectionService = game:GetService("CollectionService")
local selectedpart = CollectionService:GetTagged("OceanFloor")
for _, TaggedPart in pairs(selectedpart) do
local active = false
TaggedPart.Touched:Connect(function(hit)
if not active then
active = true
local human = hit.Parent:FindFirstChild("Humanoid")
if human then
hit.Parent.TouchingSeaFloor.Value = true
end
wait(0.1)
active = false
end
end)
TaggedPart.TouchEnded:Connect(function(hit)
if not active then
active = true
local human = hit.Parent:FindFirstChild("Humanoid")
if human then
hit.Parent.TouchingSeaFloor.Value = false
end
wait(0.1)
active = false
end
end)
end
The script above will change the TouchingSeaFloor value to true or false, which is then handled by this, which appears to work.
local human = script.Parent:FindFirstChild("Humanoid")
if human then
while true do
if script.Parent.TouchingSeaFloor.Value == true then
human.Health = human.Health - 10
human.WalkSpeed = 8
else
human.WalkSpeed = 16
script.Parent.TouchingSeaFloor.Value = false
end
wait(0.5)
end
end
It's only the top script that fails to sometimes change the TouchingSeaFloor value to false when the player stops touching the sea floor.
Nothing I found seemed to work, so any help would be appreciated :)

2 comments
you need something to break that while look (litearlly the code "break") and TouchEnded fires right after Touched gets fired
@Gameplayer365247v2 It doesn't work, just makes it more buggy. Any other ideas? Or maybe I just did it wrong?