Health Bar GUI In Roblox Studio Device Problem

19 Views Asked by At

I made an health bar in Roblox Studio, but i want it to work between devices (so it scales depending on device), the problem is, its size decreases every time you lose health, so i cant use a UIAspectRatioConstraint. I tried everything for numerous hours now and couldn't find or try anything. Any help would be very much appreciated.

Script:

local Player = game.Players.LocalPlayer
local Character = Player.Character
local Humanoid = Character.Humanoid

while wait() do
    script.Parent.Size = UDim2.new(0, (Humanoid.Health / Humanoid.MaxHealth * 225), 1, 0)
end

Like i said, i tried a lot of things. I tried rewriting the script completely, Change random values, etc.

What i expected was for the health bar to be shown on all devices without needing to use a UIAspectRatioConstraint, since it will not resize with that constraint.

1

There are 1 best solutions below

0
Tsering On

Try this code. It detects health change and maxHealth change.

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local HealthBar = script.Parent

local function UpdateHealthbar()
    local healthPercentage = Humanoid.Health / Humanoid.MaxHealth
    HealthBar.Size = UDim2.new(healthPercentage, 0, 1, 0)
end

UpdateHealthbar()

Humanoid:GetPropertyChangedSignal("Health"):Connect(UpdateHealthbar)
Humanoid:GetPropertyChangedSignal("MaxHealth"):Connect(UpdateHealthbar)