- Home /
How can I position my dynamically generated GUI boxes at the center of the screen using the screen resolution?
Hey guys, I tried making an Inventory system and I'm having this problem where I create boxes dynamically to make it look like a grid, but seem to be stuck in place no matter what the screen size is.
Here's what I currently have now:
void DrawInventory()
{
Event e = Event.current;
int i = 0;
for (int y = 0; y < slotsY; y++)
{
for (int x = 0; x < slotsX; x++)
{
Rect slotRect = new Rect(x * 60, y * 60, 40, 40);
GUI.Box(slotRect, "", skin.GetStyle("Slot"));
slots[i] = inventory[i];
item itemz = slots[i];
i++;
}
}
}
Say I assigned 5 for slotX and 3 for slotY, that would look like this:
Then I tried to center it by changing the Rect's values X and Y statically but obviously that would not be a responsive UI. I tried googling for ways but i couldnt find a solution for centering a GUI boxes generated from a for loop. I'm still new to Unity's GUI feature so if you could please provide a solution for this bug/ point me in the right direction, i would really appreciate it. Thanks everyone.
P.S. Credits for AwfulMedia's YT channel for their free tutorials. That's where i got this code.
bets advice is to adapt it to use 4.6's new GUI (you're using the legacy stuff) - it has the ability to maintain relative positions, etc. with varying resolutions.
Answer by Ijatsu · Dec 11, 2014 at 08:29 PM
I think what you want is to get the screen's size. Here's the code I'm using to place my GUI skin at the center of the screen no matter what.
GUI.skin = reticle;
GUI.Box(
new Rect(
Screen.width/2 - reticle.box.normal.background.width /2,
Screen.height/2 - reticle.box.normal.background.height/2,
reticle.box.normal.background.width/2 ,
reticle.box.normal.background.height/2),
"");
Your answer
![](https://koobas.hobune.stream/wayback/20220613173812im_/https://answers.unity.com/themes/thub/images/avi.jpg)