While loop not continuing?

I’m trying to making it so that whenever a player goes near a part. The player dies. However, Whenever i try dying for the 2nd time, It doesn’t work.

game.Players.PlayerAdded:Connect(function(plr)
	local char = plr.Character or plr.CharacterAdded:Wait()
	local RootPart = char:WaitForChild("HumanoidRootPart")
	while true do
		task.wait()
		local Distance = (game.Workspace.StarterCharacter.Hitbox.Position - RootPart.Position).Magnitude
		if Distance <= 10 then
			char:WaitForChild("Humanoid").Health = 0
		end
	end
end)

It is because you are using just the player added event. Once the player dies, you never grab their new character. Use the CharacterAdded event as well as the PlayerAdded event.
That will give you a reference to their current character. You need to end the loop once that character has been removed or has died. Add a destroying event to the character to check when it has been removed.

1 Like

Solution described as above, but will cut the loop after entering distance and to prevent the latter issue where the character dies or is destroyed.

local Players = game:GetService("Players")

local function onCharacterAdded(character)
	-- Declares humanoid and rootpart, then 
	local humanoid = character:WaitForChild("Humanoid")
	local rootPart = character:WaitForChild("HumanoidRootPart")

	local distance = (workspace.StarterCharacter.Hitbox.Position - rootPart.Position).Magnitude
	while distance > 10 and character.Parent and humanoid.Health > 0 do
		-- Distance will be checked while it is still over 10 studs away, and that character isn't destroyed nor dead
		distance = (workspace.StarterCharacter.Hitbox.Position - rootPart.Position).Magnitude
		task.wait()
	end
	-- Kill humanoid if less than 10 studs and has more than 0 health
	if humanoid.Health > 0 then
		humanoid.Health = 0
	end
end

Players.PlayerAdded:Connect(function(player)
	local character = player.Character or player.CharacterAdded:Wait()
    -- Tactical design for if character is loaded before player, calling function for the first time
	onCharacterAdded(character)
	player.CharacterAdded:Connect(onCharacterAdded)
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.