Unity 4.6 Get Textlengh in Pixels

I have a GameObject holding an Image and a Text. I now want to center the GameObject on the screen in realtime, since the text will be changing rapidly. I thought that I could read out the lengh of the text in pixels and based on that, I could center the GameObject by moving it. Btw, the Text has a custom font and FontSize. I found out that you could use CalcSize in GUIStyle, but I think that is some legacy stuff, is it? If yes, do you know a way to either read out the text lengh with a custom font and FontSize in pixels or a way to center the GameObject automaticly?

Thanks for your help.

No need for all of that. Add a Content Size Fitter to the text and set horizontal to either minimum or preferred. Leave the pivot in the middle and it should expand out either side to fit whatever text you put in it.

If you need the size just check the size of the rectTransform after adding the text.

Sorry for any typos, on my phone!


Actually you’ll want preferred for the horizontal value in Content Size Fitter, and make sure that pivot is in the middle and in the position you want the text centered on. Working from memory as I don’t have access to unity!