Simple text problem, no simple solution

Hey there!

What I'm trying to achieve, is a simple button with a price and a currency icon.
I need the text and icon to be centred on the button.

This is however not as easy as it sounds.
For me to anchor the text to the currency icon, or vice-versa, I need the text to be aligned on the side.
Now how do I centre the text on the button, while the text is aligned to the side?

I will need to know the size of the text itself, and not just the bounding box.

I've had a similar problem using NGUI.
Here I would just use a label with the ReesizeFreely option on, this way the text will always fit the size of the bounding box. And I can use centre alignment and anchor the currency icon on the side.
Only downside to this solution, is of course that a large enough number will exceed the boundaries of the button.

I think this is a pretty common UI problem, so I would like to hear people's approach.

Cheers :smile:

1 Like

Also I have had a similar problem in past but I was unable to solve (with ngui) ...
I would like to know it me too how to make, if possible :)

(sorry for my english)

drag that blue ring (pivot) from middle of text to middle of button?

It would be good if rich text supported sprites :) then it would just auto center.

This is a bit tricky...
1) Right-click on the button --> "Create Empty". The new GameObject will be automatically positioned and aligned to the center of your button
2) To the new object, add components Layout - Horizontal Layout Group and Layout - Content Size Fitter, for the latter choose "Horizontal Fit - PreferredSize"
3) parent both icon and button text to this new object

1745668--110270--text and icon.png

6 Likes

Looks great Melang!

Will give it a try :-)

1 Like

Great, i have succeeded!
Thank you very much

3 Likes

Works like a charm!

looked for same solution for currency shop

In my case I also need to add a LayoutElement to the icon image with preferred width, and tick control child size in HorizontalLayoutGroup




1 Like

This works! :) Thanks

1 Like