- Home /
Self-resizing text and background
I'm a bit confused by all the various components and the new (to me) Unity UI in general.
Let's say I want to have self-resizing text elements with a background image fitting the size of the text.
My first approach was to just have a single GameObject and add text and/or image components as necessary. Well, that's not allowed - text and image cannot be on the same GameObject, it seems.
So I went on to write some code that generated several GameObjects in a hierarchy. And because not all elements will have a background image, and not all will have text, I'd like to generalize it all of it as in the following UI element hierarchy:
Element
Background Image
Text
Now, I figured out this doesn't work because the Text actually needs to be a child of the background image in order for transparency and so on to work out. So it's actually
Element
Background Image
Text
Shame about that. But here come my as of yet unresolved troubles - where do I put all the various Unity UI components?
Obviously the text component goes into the text GameObject and the image component goes onto the Background Image GameObject.
But where do I put ContentSizeFitters? LayoutElements?
Which pivots and anchors do I set to what? Where do I change preferredSizes and rect sizes and in what ways?
What do I need to do when the text changes? When I need to reposition an element? When the screen size changes?
Also, I'd like to be able to automate it all through code, so if you can please explain it as if the editor didn't exist.
Sorry about the vagueness of the question; I'm still wrapping my head around all this UI system.
Before going into an answer, I'd like to suggest you try out a "Canvas". Children of a Canvas use RectTransforms, rather than regular transforms, which include stuff like anchors. Canvases also have the optionaly-ability to automatically resize their contents based on screen size. I'd also suggest you add some built-in components, like an InputField to the canvas, and see how unity organizes the various gameobjects, and components that make up the control.