How to cancel loop from touching event?

Hi,
I made script that start a loop after player touch something, but when player no longer touch something the loop still works why? How can i stop the loop?

Heres the function:

HumanoidRootPart.Touched:Connect(function(hit)
repeat wait(1)
	 	   if deb.Value == true and npc.health.Value >= 0 then
	           npc.health.Value = npc.health.Value - damage
	       end
 until npc.health.Value <=0

   if npc.health.Value <= 0 then
		   Player.leaderstats.Gold.Value = Player.leaderstats.Gold.Value + Zone.Value 
	       wait()
	       npc:Destroy()
   end
end)

so when im no more touching the part it still damages the npc. How to stop it?

npc - a model with my npc
health - number value in npc that says a “health”
Zone - number value
deb - a bool value object that says if player is able to deal damage

2 Likes

There nothing in the code that says the loop should stop unless the npc health is 0. You need to add something that tells the loop that the part isn’t touching anymore.

1 Like

You can use break, it basically will stop your loop unless said otherwise.

Read more about it here: Introduction to Scripting | Documentation - Roblox Creator Hub

1 Like