Implementing a Chat layout in Unity

Implementing a Chat layout in Unity

In this post, I want to share with you a small template that you can use when creating a chat screen layout.

This is not a working example of a chat system. It’s only about the layout.

I implemented this a few years back and I remember that It took me quite some time to figure out the correct arrangement of components to get the desired effect.

Most chat screens layout work in the same way:

  1. A vertical list of messages with newer in the bottom;

  2. Player messages are aligned to the right of the screen while others are aligned to the left;

  3. Each message bubble expands to a max width before breaking into new lines.

The first step is quite easy to achieve:

  • A ScrollRect with a Content made of a VerticalLayoutGroup with a ContentSizeFitter aligned to the bottom;

Now, the other steps are a little bit more tricky.

The bubble size is defined by the message text length. But the bubble also needs to have a background image and adjust not only horizontally but also vertically to the content.

This was how I was able to achieve it:

Top Container

Message Container

Text Message

  • Text - adds the message text;

To have different messages for both the player and others, I’ve used two different prefabs and selected the correct alignment - left or right - in the Child Alignment property of the HorizontalLayoutGroup.

In terms of behavior, the Chat.cs script is the main controller.

It holds the prefabs for both the player and others and you can configure the bubble maximum width in terms of a percentage of the total screen width.

Check the complete example here.