PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

Size

GuiObject

UDim2

This property determines a GuiObject|GUI's scalar and pixel size using a UDim2. Its value can be expressed as UDim2.new(ScalarX, PixelX, ScalarY, PixelY) or ({ScalarX, PixelX}, {ScalarY, PixelY}).

The scalar size is relative to the scalar size of parent GUI elements, if any. For example, if the GUI’s scalar size is UDim2.new(0.5, 0, 0.5, 0) and it is not the descendant of a GUI, then it will occupy half of the screen horizontally and vertically. However, if the GUI is the child of a GUI with a scalar size ofUDim2.new(0.5, 0, 0.5, 0), then the GUI’s scalar size will render to be half the scalar size of its parent both horizontally and vertically and will occupy a quarter of the screen in both dimensions.

The pixel portions of the UDim2 value are the same regardless of the parent GUI’s size. The values represent the size of the object in pixels. For example, if Position is set to {0, 100}, {0, 150} the element will render with a width of 100 pixels and height of 150 pixels.

If the GUI has a parent, its size of each axis is also influenced by the parent’s GuiObject/SizeConstraint.

Although it is possible to use negative sizes when creating GUIs, it’s more often better to manipulate GuiObject/AnchorPoint instead.

An object’s actual pixel size can be read from the GuiBase2d/AbsoluteSize property.


Code Samples


Health Bar

This code sample allows you to create a simple color-changing health bar using two nested Frames. Paste this into a LocalScript on the inner frame.

local player = game.Players.LocalPlayer

-- Paste script into a LocalScript that is 
-- parented to a Frame within a Frame
local frame = script.Parent
local container = frame.Parent
container.BackgroundColor3 = Color3.new(0, 0, 0) -- black

-- This function is called when the humanoid's health changes
local function onHealthChanged()
	local human = player.Character.Humanoid
	local percent = human.Health / human.MaxHealth
	-- Change the size of the inner bar
	frame.Size = UDim2.new(percent, 0, 1, 0)
	-- Change the color of the health bar
	if percent < .1 then
		frame.BackgroundColor3 = Color3.new(1, 0, 0) -- black
	elseif percent < .4 then
		frame.BackgroundColor3 = Color3.new(1, 1, 0) -- yellow
	else
		frame.BackgroundColor3 = Color3.new(0, 1, 0) -- green
	end
end

-- This function runs is called the player spawns in
local function onCharacterAdded(character)
	local human = character:WaitForChild("Humanoid")
	-- Pattern: update once now, then any time the health changes
	human.HealthChanged:Connect(onHealthChanged)
	onHealthChanged()
end

-- Connect our spawn listener; call it if already spawned
player.CharacterAdded:Connect(onCharacterAdded)
if player.Character then
	onCharacterAdded(player.Character)
end