- Home /
Force Unity UI element to refresh/update?
I have a Button element with a Content Size Fitter set to preferred size. The goal is to make the Button's RectTransform resize automatically based on its text. However, I noticed that the rect doesn't automatically resize when new text is pushed to its child's Text component. It only resizes when the child's values change (e.g. if I manually change the font size) or when the button is selected.
Is there any way to manually force Unity to "update" the button as soon as the text changes? I know about Button.Select()
, but I have two buttons visible at the same time, and I want all of this to happen in one frame.
Here's an example of what the buttons look like when they're first set to active and populated with text:
And here's what they look like after the bottom one is highlighted:
Answer by losingisfun · Jan 21 at 05:54 AM
https://forum.unity.com/threads/force-immediate-layout-update.372630/
This will do what you want in regards to fixing up layouts from things like ContentSizeFitters and VerticalLayoutGroups.
The easiest use for this would be:
LayoutRebuilder.ForceRebuildLayoutImmediate(transform as RectTransform);
Answer by donutLaserDev · Mar 21, 2018 at 02:06 PM
Perhaps, this might help? https://docs.unity3d.com/ScriptReference/RectTransform.ForceUpdateRectTransforms.html
Thanks, good to know this exists. Seems it still doesn't work on the same frame that the button is set active, though.
The Button seems to fix itself one frame after being set active, once the Text component has no pre-existing text at the start of the convo. It's not really a solution, but right now I'm working around the problem by making the method a coroutine and just hiding the buttons for one frame so that the RectTransform can correct its size.
I see the same thing, i.e. ForceUpdateRectTransforms() isn't doing anything, at least not within the frame that I'm instantiating my UI. I have to do a goofy workaround in Update() to get the size of the UI element I'm interested on the next frame after it's been instantiated.
Answer by vElumi · Sep 09, 2019 at 04:53 PM
image.SetAllDirty();
from forum: (https://forum.unity.com/threads/ui-elements-stuck-need-refresh.269539/)
Answer by Laiken · Jan 18, 2021 at 01:46 PM
Maybe LayoutRebuilder.ForceRebuildLayoutImmediate can be useful for that case
https://forum.unity.com/threads/force-immediate-layout-update.372630/