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:
1 | Player = game.Players.LocalPlayer |
2 | ScreenGui = Player.PlayerGui:WaitForChild( "ScreenGui" ) |
3 | Gui = ScreenGui.Frame |
4 | MiddleOfGui = math.floor(Gui.Position/ 2 ) |
5 | print (MiddleOfGui) |
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
01 | Player = game.Players.LocalPlayer |
02 | ScreenGui = Player.PlayerGui:WaitForChild( "ScreenGui" ) |
03 | Gui = ScreenGui.Frame |
04 |
05 | wait() -- wait is crutial, it won't be absolute unless you give it time to set up |
06 | absoluteXS = Gui.AbsoluteSize.X |
07 | absoluteYS = Gui.AbsoluteSize.Y |
08 |
09 | absoluteXP = Gui.AbsolutePosition.X |
10 | absoluteYP = Gui.AbsolutePosition.Y |
11 |
12 | MiddleOfGui = UDim 2. new( 0 , absoluteXP + (absoluteXS/ 2 ), 0 , absoluteYP + (absoluteYS/ 2 )) |
13 |
14 | 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:
1 | MiddleOfGuiX = Gui.Position.X-Gui.Size.X/ 2 |
2 | MiddleOfGuiY = Gui.Position.Y-Gui.Size.Y/ 2 |
3 | MiddleOfGui = UDim 2. new(MiddleOfGuiX, 0 , MiddleOfGuiY, 0 ) --In a UDim2 form, works just the same. |