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

Help with getting the middle of a Gui?

I was trying to get the middle of the GUI but I got an error saying:

Output: Players.Player.PlayerGui.LocalScript:4: attempt to perform arithmetic on field 'Position' (a userdata value)

Why did I get this error and how do I fix it?

LocalScript:

Player = game.Players.LocalPlayer
ScreenGui = Player.PlayerGui:WaitForChild("ScreenGui")
Gui = ScreenGui.Frame
MiddleOfGui = math.floor(Gui.Position/2)
print(MiddleOfGui)

2 answers

✓ Accepted answer

The key to finding the center, no matter what screen, is going to be using AbsolutePosition and AbsoluteSize. These two will get you the pixels away from the top-left corner it is even with XScale and YScale

Player = game.Players.LocalPlayer
ScreenGui = Player.PlayerGui:WaitForChild("ScreenGui")
Gui = ScreenGui.Frame

wait() -- wait is crutial, it won't be absolute unless you give it time to set up
absoluteXS = Gui.AbsoluteSize.X
absoluteYS = Gui.AbsoluteSize.Y

absoluteXP = Gui.AbsolutePosition.X
absoluteYP = Gui.AbsolutePosition.Y

MiddleOfGui = UDim2.new(0, absoluteXP + (absoluteXS/2), 0, absoluteYP + (absoluteYS/2))

print(MiddleOfGui)

Hopefully this helps

It's impossible to divide a UDim2(positioning/size used for GUIs) by a number, as the UDim2 consists of 4 numbers: X, XOffset, Y, YOffset. So, this code should work here:

MiddleOfGuiX=Gui.Position.X-Gui.Size.X/2
MiddleOfGuiY=Gui.Position.Y-Gui.Size.Y/2
MiddleOfGui=UDim2.new(MiddleOfGuiX, 0, MiddleOfGuiY, 0) --In a UDim2 form, works just the same.

1 comment

0

Actually.... this wouldn't work. This is to get the edges of a GUI. To get the center just simply use it's position. (Gui.Position)

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