Trouble with my code working after player leaves part

I want to make a script that plays an audio and takes -20 damage to the player while they’re touching the part. The code works just how I want it to, but it continues to work even after the player leaves the part and only ends when they die.

part = script.Parent
sound2 = script.Parent["scp cough 2"]
sound1 = script.Parent["scp cough 1"]

local debounce = false
local function onPartTouched(other)
	if debounce == true then
		return
	end
	debounce = true
	local hum = other.Parent:FindFirstChild("Humanoid")
	while true do

		task.wait(1)
		sound1:Play()
		print("sound1")
		task.wait(2)
		sound2:Play()
		print("sound2")
		task.wait(1)
		hum.Health -= 20
		print(hum.Health)
		if hum.Health == 0 then
			break
		end
		if part.Touched == false then
			debounce = false
		end
	end
	debounce = false
end
part.Touched:Connect(onPartTouched)

Any help is greatly appreciated.

local sound2 = part:FindFirstChild("scp cough 2")
local sound1 = part:FindFirstChild("scp cough 1")

local function onPartTouched(other)
	local hum = other.Parent:FindFirstChild("Humanoid")
	if hum then
		-- Player touched the part
		sound1:Play()
		wait(2) -- Wait for sound1 to finish playing
		sound2:Play()
		wait(1) -- Wait for sound2 to finish playing
		hum.Health = hum.Health - 20
		print("Player health:", hum.Health)
	end
end

part.Touched:Connect(onPartTouched)
1 Like

The code you just provided is wrong

Either connect a loop when Touched is called & disconnect it when TouchEnded is called, or utilize BasePart:GetTouchingParts() in the Touched loop