I just started using anchors and stretching elements to scale my UI dynamically so that width and height of the device can vary and its working very well so far. I’m trying to build a messaging view; typically what you would see on an iPhone, Android, etc, but I’m trying to make the padding dynamic so that when stretched there is always a maximum ratio at which the message can expand (let’s say, always 80% of the screen) regardless of how wide the canvas is. In the layouts I can set my Right or Left padding statically in units but that doesn’t stretch when the canvas width changes. I’m using nested layouts to get the effect that I need, to adapt the bubble to the text width, and that works. This is all taking place inside a ScrollView. The opponent in the conversation should be left justified, and the player should be right justified, which is where the problem is created, otherwise I would just be able to change the anchors.
In the picture I’ve attached, the red area should always scale accordingly as the canvas stretches, as should the max width of the message. Some messages should not stretch to the full maximum based on text length (like ‘yes’, or ‘OK that’s great’).
Here’s my hierarchy. I’m using abbreviations (VLG = vert layout group, h = horiz)
Canvas - Canvas Scaler (Scale with Screen Size)
Scroll View - Scroll Rect
Viewport - Mask
Content - VLG, Content Size Fitter (Vert set to preferred, Horiz unconstrained)
Player1Message - VLG (Child Width Force Expand, upper left aligned)
BubbleBackground - HLG (Child Width Force Expand, middle center aligned, some padding), Image
Arrow - Image
Text
Player2Message - VLG (Child Width Force Expand, upper right aligned)
...
Message(n)
ScrollBar
I assume I need to do something with FlexibleWidth set to .8 on the message and .2 on the spacing, but it gets ignored it seems. I tried putting a parent above Message with a horizontal layout group and an empty child object with a layout and a placeholder image but it just gets squeezed down. If I duplicate messages and put them on the same parent and apply flexible widths of .8 and .2, they both take up 50% of the space. I think the text is driving the max message width when I need it to drive only the height and width up until the ratio limit I’ve defined.
I also thought about copying the UI Layout Group script and extending it to replace padding units with a ratio based on the canvas width, but that seems kind of tacky. Is there a way to do this with just the UI elements? How do you guys recommend I structure this?