How to make a gui resize based on the amount of text inside

The title basically explains it.
If I have a textbox with 20 characters in it I want to add that to the X offset of the gui plus a little, the current code I have is:

while wait() do
script.Parent.Size = UDim2.new(0, (#script.Parent.Text+5),0,100)
end

but it does not add the +5.

2 Likes

There’s a page on the wiki that could better tell you how to achieve this.


Plus the way you’re doing it wouldn’t work because it would infinitely loop. There’s nothing telling it when to stop. Even then it’d only add the 5 once since you’re only adding it from the length of the string and not the actual size of the UI object.

2 Likes

It will work if there’s an external factor changing the text of the GUI element.
Here’s a little thing to test that:
LocalScript inside a TextLabel

script.Parent.Text = "This text has a length of 28"
print("length + 5: " .. #script.Parent.Text + 5)
while true do
	local newSize = UDim2.new(0, #script.Parent.Text + 5, 0, 100)
	print(newSize)
	script.Parent.Size = newSize
	wait(1)
end

LocalScript inside StarterPlayerScripts

while true do
	wait(1)
	local textLabel = game.Players.LocalPlayer.PlayerGui.ScreenGui.TextLabel
	textLabel.Text = textLabel.Text .. " string"	
end
1 Like

I would recommend using Textbox.TextBounds.X or Y. This will return the x or y size of the text, but not the size of the text box itself. If you want to use the textbox’s size use Textbox.Size.

For example:

while wait() do
script.Parent.Size = UDim2.new(0, (#script.Parent.Text.TextBounds.X+5),0,100)
end

or

while wait() do
script.Parent.Size = UDim2.new(0, (#script.Parent.Text.Size.X+5),0,100)
end
2 Likes

I suggest using events instead of infinite loop to detect text change.
You can use GetPropertyChangedSignal method.

Gui:GetPropertyChangedSignal("Text"):Connect(function()
    -- resize here
end)
5 Likes

I would not use offset EVER for a UI, the reason is that on smaller devices there is less pixel real estate, so a UI that is small on a laptop ends up colossal on for instance an iphone 4. Always use scale for UI unless you’re working in minuscule increments.

5 Likes

Oh thanks, I somehow never knew that existed! Will be sure to use that in the future.

1 Like

local normally = script.Parent.TextBounds.Y
script.Parent:GetPropertyChangedSignal(“Text”):Connect(function()

if script.Parent.TextFits == false then
	
	script.Parent.Size = UDim2.new(script.Parent.Size.X.Scale,0,script.Parent.Size.Y.Scale,script.Parent.TextBounds.Y)
end

script.Parent.Size = UDim2.new(script.Parent.Size.X.Scale,0,script.Parent.Size.Y.Scale,script.Parent.TextBounds.Y-normally)

end)

5 Likes

If anyone needs to know the solution to this problem in the future (like I did).There is now a property called AutomaticSize that can resize your Gui based on what’s inside it.

13 Likes