You can center your left-aligned text without Layout-Groups.
For a simple Setup create a Canvas.
- Add a new Image-Object. 500 wide, 100 heigh, Color = Black. Name it DialogueBox.
- Add a new GameObject as a child of the DialogueBox. 480 wide, 80 heigh. Name it TextBounds.
- Add a new TMP-Object as a child of the TextBounds. From the Anchor-Presets choose Stretch-Stretch while holding Shift+Alt (or manually set Anchor Min = 0, 0; Max = 1, 1; Pivot = 0.5, 0.5). Name it DialogueText.
- Create the following script and add it to your DialogueText.
public TMP_Text tmpText; // Assign DialogueText in the Inspector
private void AssignString(string s)
{
// Assign Text to TextObject
tmpText.text = s;
// Updates the Text-Mesh
tmpText.ForceMeshUpdate();
// Get TextBounds and use TextBounds to position the Text-Parent
Bounds bounds = tmpText.textBounds;
Vector2 newPos = new Vector2(-bounds.center.x, -bounds.center.y);
RectTransform rt = tmpText.transform.parent.GetComponent<RectTransform>();
rt.localPosition = newPos;
}
Use this function to assign your string to the DialogueText-Object.
Your text should now be centered within the black rectangle.
Text-Position without the script
Text-Position with the script
The longest line of text always has as much room on left side as it has on the right side.