Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do i make a GUI's Size Equal to a NumberValue?

I made an energy GUI and im trying to make a NumberValue the same as a NumberValue so when the Number Value decreases the Gui decreases

local player = game.Players.LocalPlayer
local Gui = script.Parent
local EnergyValue = script.Parent.EnergyValue
wait(1)
Gui.Size.UDim2 = EnergyValue.Value
EnergyValue.Changed:connect(function()
	Gui.Size.UDim2 = EnergyValue.Value
	
end)


1 answer

✓ Accepted answer

UDim2 is like Vector3, it is a data type and not a property and similarly to Vector3, you need to declare it as UDim2.new(). UDim2.new() requires 4 values, a Scale and an Offset for both X and Y. An example would be this:

Gui.Size.X = UDim2.new(Sx, Ox, Sy, Oy) -- S being Scale and O being Offset.

How you would want to change the size depends the values you are using. Scale is a decimal number and Offset is an integer. The Scale is a percentage of the Screen and Offset is an exact pixel number. For example, if you said:

Gui.Size = UDim2.new(0.5, 0, 0, 0)

then the Gui would take up half the screen or 50%. If you say did this:

Gui.Size = UDim2.new(0, 5, 0, 0)

then your Gui would only be 5 pixels wide. The reason for Scale is to make it easier to make everything look the same size and have the same position relative to the screen size. The reason to use offset is to make everything the same size and position period, no matter the screen size. Another benefit of using Scale is that it changes depending on the parent. For example, if you had a button inside a frame and you wanted the button to take up half the space of the frame, then the scale would still be 0.5.

That being said, lets use scale. Because scale needs to be a percentage, go ahead and create another value and call it EnergyMax and put it to the max energy the player can have. Now lets use it all

local player = game.Players.LocalPlayer
local Gui = script.Parent
local EnergyValue = script.Parent.EnergyValue
local MaxEnergy = script.Parent.MaxEnergyValue --The max I was talking about
wait(1)
Gui.Size = UDim2.new(1, 0, (EnergyValue.Value/MaxEnergy.Value), 0) --The "bar" is completely full and it will decrease vertically. 

EnergyValue.Changed:connect(function()
    Gui.Size = UDim2.new(1, 0, (EnergyValue.Value/MaxEnergy.Value), 0) -- This will give you the percentage of energy left and the Gui will grow or shrink according to the Max value. 
end)

More on UDim2 here

2 comments

1

that doesn't work, UDim2 is read-only, you'll need to set size, not y or x.

0

Your right, been a while since I used it.

This discussion is preserved as it was. New answers, comments, and votes are closed.