- Home /
GridLayoutGroup requires a single frame till it does layout? thus giving incorrect element positions in Awake/OnEnable
Hi all,
so in my inventory I've been recently using a GridLayoutGroup
for my slots. The inventory takes items as data (by names) in editor, and looks up a database to allocate those items. (e.g. data["it0"] = "Handgun") - I do the item allocation/initialization in OnEnable. I allocate the necessary UI elements for the item (Button, Image, etc) and position it correctly with the right scale etc in the inventory.
The thing is, to properly position the item I'd have to access the position of my slots, which are contained within the GridLayoutGroup
. I noticed if I try to access the position of the slots in Awake/OnEnable I get incorrect results. If i do it later (say skip a single frame) in Update it then gives me correct results!
I tried a few things to manually trigger the layout, but nothing seemed to work. e.g.
LayoutBuilder.MarkLayoutForRebuild(slots_parent);
and a bunch of grid/layout functions: CalculateLayoutInputHorizontal, CalculateLayoutInputVertical
Here is my grid settings:
Here is a video demonstrating the problem. Please consider watching it.
Notice:
The first time I run the game, items are not positioned correctly
I then reset and re-initialize items manually from editor while the game is running, it positions correctly
I then don't do the allocation in my
initialize()
but inUpdate()
after skipping a frame or two. It works just fine.This is obvious, but the same code is used in all 3 cases.
Why is this happening and how to avoid it? Is there anyway I could trigger the layout manually from code, so I don't have to do this ugly hack of waiting a single frame before allocating items?
Thanks in advance, any help is appreciated!
Doesnt this mean you should use Start ins$$anonymous$$d of Awake? Its still before Update.
I do notice with a canvas that it REALLY likes to resize itself on every resolution change. You have to make sure that it is the canvas that is properly set-up. If the Canvas is initialised before the screen is setup it is very likely that the configuration will come out incorrectly.
Also can you simply fire a coroutine to wait one or two frames?
OnEnable()
{
StartCoroutine(Funcatron());
}
IEnumerator Functatron()
{
yield;
//yield;
//DoStuff;
}
Hey, I have got the same issue. It's been several years since you posted a question, did you find any technique to get correct positions in Awake?
Your answer
Follow this Question
Related Questions
GetComponent() Problem with getting value. 1 Answer
Move a UI element with respect to canvas scaler 0 Answers
UI scrollable rect, get position on content based on mousePos. 0 Answers
Unity2D Grid disappears when zooming out 0 Answers
Content size fitter does not update rect transform immediately 1 Answer