Content Shift with Text Length

22 Feb 2019

So you have some text in Unity and the problem is you want content next to the text to move when the length of the text increases, but when you try to do it, it seems impossible without scripts.

The image below shows how the blue box stays in the same place when the text length increases. What we want is the blue box to shift over when the score increases. I will show you a solution to this problem without using scripts.

The first step is to add a Content Size Fitter component to the text object. Set the Horizontal Fit and Vertical Fit to Preferred Size. This will make the bounding box of the text always match the size of the text. So when there is more text, the box will become larger.

To make the content shift to the side when the text increases in length, you will need to set is as the child of the text. Since we want our content to shift to the right, we will anchor the content to the middle right of the text. If you want it to shift to the left then you would anchor it to the middle left.

Now when you type more text, you will see that the content will be shifted to the right. You will also notice that the text will grow in size from the centre. This is ok if that’s what you want from the layout but I want to make it so the text will stay align to the left and only expand to the right.

To keep the text aligned to the left, you will need to set the pivot point to the left of the text. To do this you can drag the blue circle to the left side of the text, or you can set the pivot point’s x coordinate to 0. If you want the text to grow to the left then set the pivot point’s x coordinate to 1.

Now when the text increases in length, the content will be shifted to the right. You can do this with any UI element including buttons or other text.