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.
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.
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