ZHexZHex
ZHexZHex

Reputation: 1

Health Bar GUI In Roblox Studio Device Problem

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.

Upvotes: 0

Views: 333

Answers (2)

OeTiao
OeTiao

Reputation: 1

I believe I have an answer for that, and it's easy and simple, no code needed. The problem is that the UI you made has to have a size that is proportional to the screen size, right? My solution is that you used the offset value to scale your GUI, but, instead, you have to use the scale value. Here's an example: X Size {0,10} Y Size {0,10}. The reason why this won't scale proportional to the screen's size is because I set the size values in pixels, but I have to set it in percentage of the screen's size, so, instead of doing this: X Size {0,10} Y Size {0,10}, I do this: X Size {0.1,0} Y Size {0.1,0}. By moving my size value to the first number, it will scale according to the screen size. Remember that the 0.1 that I set will NOT have the same size as the 10 I set before, but you can fix that by resizing the UI manually to how it was before.

Here are some images to help you: https://i.sstatic.net/uPTl7.png

In this picture, you can see that the scale property is equivalent to the first value in the X size property.

If you still didn't understand, you basically have to change the size property from Offset to Scale, since Scale automatically maintains the same ratio of size for any device.

https://i.sstatic.net/JafoO.png

Upvotes: 0

Tsering
Tsering

Reputation: 483

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)

Upvotes: 0

Related Questions