Help with a script that breaks when the player respawn

Hello
I need help with a problem with my script:

The script breaks when the player respawn

Players.PlayerAdded:Connect(function(LocalPlayer)
	
	local leaderstats = LocalPlayer:WaitForChild("leaderstats")
	
	local Food = leaderstats:WaitForChild("Food")

	local Water = leaderstats:WaitForChild("Water")
	
	local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
	local Humanoid = Character:WaitForChild("Humanoid")
	
	Humanoid.HealthChanged:Connect(function()
		if Humanoid.Health <= 0 then
			Humanoid.Health = 0
		else
			if Humanoid.Health >= 100 then
				Humanoid.Health = 100
			end
		end
	end)
	
	Food.Changed:Connect(function(NewValue)
		if NewValue <= 0 then
			Humanoid.Health -= 5
		end
	end)
	
	Water.Changed:Connect(function(NewValue)
		if NewValue <= 0 then
			Humanoid.Health -= 5
		end
	end)
end)

Please help me

You should add CharacterAdded event

1 Like

Like Katanix_656 said a CharacterAdded Event should fix this issue.

Players.PlayerAdded:Connect(function(LocalPlayer)
	LocalPlayer.CharacterAdded:Connect(function()
local leaderstats = LocalPlayer:WaitForChild("leaderstats")
	
	local Food = leaderstats:WaitForChild("Food")

	local Water = leaderstats:WaitForChild("Water")
	
	local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
	local Humanoid = Character:WaitForChild("Humanoid")
	
	Humanoid.HealthChanged:Connect(function()
		if Humanoid.Health <= 0 then
			Humanoid.Health = 0
		else
			if Humanoid.Health >= 100 then
				Humanoid.Health = 100
			end
		end
	end)
	
	Food.Changed:Connect(function(NewValue)
		if NewValue <= 0 then
			Humanoid.Health -= 5
		end
	end)
	
	Water.Changed:Connect(function(NewValue)
		if NewValue <= 0 then
			Humanoid.Health -= 5
		end
	end)
 end)
end)
3 Likes

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