Suppose mystring is a string variable (whose value changes over time) and that myIcon is a texture or sprite of known dimension, say 32x32.

Is it possible to write a Unity script that draws myIcon alongside myStringlike this example (where myString is "TURTLE" in this case):

enter image description here

In particular, I have the following challenges:

  • I would like the whole construction (icon + string) to be horizontally centered on the screen).
  • The spacing between the icon and the text should be some fixed number of pixels.
  • Since the pixel width of the string changes when the value of the string changes, the appropriate horizontal positioning of the icon and the text will also change and can't be easily calculated in advance.

So, my question is: how can I draw and center such a GUI element using a Unity script?

The obvious way to do this would be to have myIcon inline in the text label, but I read that this isn't possible with unity's current GUI implementation.

It also looked like this might be possible using a horizontal layout group, but I couldn't find a clear guide on how to implement that in a script.


Use manual anchoring instead of using layout groups if it's not a must.

Keep both logo and text UI objects in an empty UI object. Manually anchor both objects as your intended layout. They are children of an empty parent so you can move, scale, rotate parent as you want and place the anchors manually for parent. This way icon and text layout won't change as they are children, unless you change display orientation.

Get the UI text object with iconName = gameObject.GetComponent<Text>(); and update with iconName.text = "string"; as you need from script. Use suitable setup for text UI object such as Best Fit, Alignment etc.

enter image description here


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.