Loop repeats too fast even though there Is a wait

Hi,
Ive been trying to make a system where if the player is in water then they start to lose health (because the map is a snowy island and the water is really cold). Everything is working except, the loop that I run when the player is in the water repeats very quickly and kills you instantly even though there Is a wait.

Code
local LocalPlayer = game:GetService("Players").LocalPlayer
function Update(dt)
	local Character = LocalPlayer.Character
	if not  (Character)  then
		return
	end
	local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
	if not (HumanoidRootPart) then
		return
	end
	local min = HumanoidRootPart.Position - (4 * HumanoidRootPart.Size)
	local max = HumanoidRootPart.Position + (4 * HumanoidRootPart.Size)	
	local region = Region3.new(min,max):ExpandToGrid(4)
	local material = workspace.Terrain:ReadVoxels(region,4)[1][1][1]
	if material == Enum.Material.Water then
		while true do
			Character.Humanoid:TakeDamage(15)
			wait(2)
		end
	end
end
game:GetService("RunService").Heartbeat:Connect(Update)

Im thinking it might be the heartbeat thing I added which someone here on the devforum recommended.

Thanks In Advance :grinning:

try

while wait(2) do
end

yeah that still doesn’t work :confused:

seems really strange, is this a Roblox bug, or because of the heartbeat thing?

It’s because RunService.HeartBeat fires many times a second. Every second it will make 20+ connections, so even though each connection waits they are independent of each other.

so how should I connect the Update function?

I didnt notice the heartbeat event.
Heartbeat loops through it regardless of whats inside it thus creating multiple while loops.

so how do you think I should connect the update function?

Damage the player once instead of using the while loop, since the script is already connected to a Heartbeat event and that might be the solution

Just change the heartbeat with while wait() do loop.

example:

local LocalPlayer = game:GetService("Players").LocalPlayer
while wait() do
	local Character = LocalPlayer.Character
	if not  (Character)  then
		return
	end
	local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart")
	if not (HumanoidRootPart) then
		return
	end
	local min = HumanoidRootPart.Position - (4 * HumanoidRootPart.Size)
	local max = HumanoidRootPart.Position + (4 * HumanoidRootPart.Size)	
	local region = Region3.new(min,max):ExpandToGrid(4)
	local material = workspace.Terrain:ReadVoxels(region,4)[1][1][1]
	if material == Enum.Material.Water then
		while true do
			Character.Humanoid:TakeDamage(15)
			wait(2)
		end
	end
end

Thanks It worked exactly as expected! :grinning:

1 Like