I want to implement UI layout in Unity:
And here's what I've already done in Unity using an scroll view and putting a Vertical Layout Group
and a Content Size Fitter
on its content
Now the problem is because I'm using Vertical Layout Group
on scroll view's content I'm unable to assign the x value of these chat bubbles because I have to align the other user's chat bubbles to the left and align the self chat bubbles to the right just like the first image. Any ideas on that?
-
1\$\begingroup\$ Hint: not every GameObject is one you see. You can vertically stack "slices" that span the whole width of your chat, then horizontally align the speech bubbles and icons within that "slice" container. \$\endgroup\$– DMGregory ♦Jul 7, 2019 at 11:39
-
\$\begingroup\$ How a bubble's width and height are computed? \$\endgroup\$– trollingcharJul 8, 2019 at 7:55
1 Answer
Here is a quick proof of concept of how I would do this:
Wrap each text bubble in another object which has the width of the whole chat box.
- The ChatBox has a Vertical Layout Group with "Force Child Expand" on. This causes the "Wrapper" child objects to always have the width of the full chat box.
- The "Wrapper" child objects is solely responsible for defining the space in which the chat bubble should be aligned. You might want to hide this object by removing the
Image
andCanvasRenderer
components so it's nothing but aRectTransform
. I just left them visible in this screenshot to better illustrate what is going on. - The "ChatBubble" is then placed within the "Wrapper". To switch between left-aligned and right-aligned boxes, set the
Anchor
andPivot
positions like this:
You can use the Width of the ChatBubble and the Height of the Wrapper to control the horizontal and vertical size of the bubble.