Well I see some problems with the code. Firstly, your connection a new event handler function to Humanoid.Health changed every 1 second! There is no reason to do this, you only need to connect it once. Second, you cannot change the scale property of a Udim2 directly as it’s immutable, you would have to create a new UDm2 value.
Additionally, your setting the “Health” variable once to Humanoid.Health. But your not updating that whenever the health changes, so when you calculate the new HealthBar.Size.X.Scale your actually just using the same value.
if Humanoid.Health < 85 then
print("in danger!")
Player.PlayerGui.UserInterface.DangerLabel.Visible = true
wait(10)
Humanoid.Health += 5
else
Also waiting inside the while loop while adding health is a bad idea, because if the player’s health changes while your script is yielding, it will still run the Humanoid.Health += 5 after the yield is over. Also there is a chance of “dead code running” if this script is cloned every-time the character respawns (if having Gui.ResetOnSpawn enabled)
Last issue is Humanoid.Health is being updated on the client! Which is not what we want we want it to be updated on the server so it replicates. So what I would recommend is splitting the healing code into a server script while the UI logic into a local script inside the UI.
Here is the code implemented fixing these issues,
Here would be the healing logic implemented
local RunService = game:GetService("RunService")
local HealSpeed = 5
RunService.Heartbeat:Connect(function(Delta)
for i,v in game.Players:GetPlayers() do
if v.Character == nil then continue end
if v.Character:FindFirstChild("Humanoid") == nil then continue end
if v.Character.Humanoid.Health < 85 then
v.Character.Humanoid.Health += Delta * HealSpeed
end
end
end)
Here would be the UI logic implemented
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local UserInterface = Player.PlayerGui:WaitForChild("UserInterface")
Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
local Health = Humanoid.Health
local HealthBar = UserInterface.HealthBG.HealthBar
HealthBar.Size = UDim2.fromScale(Health/100, HealthBar.Size.Y.Scale)
UserInterface.DangerLabel.Visible = if Humanoid.Health < 85 then true else false
end)