- Home /
Resize sprite to 3D text
Hello all! I have been messing with Unity's new 2D system and I am trying to make a simple sign.
When the player walks past the sign I currently have a sprite and 3D text that appears above it.
For example, when the user walks past the first sign it will appear above a background sprite and 3D text with the sentence "Press 'space' to jump".

The entire sentence can be changed to anything from the lines of "Press 'left shift' to fire", "Press 'e' to fire" or "Stars can be collected to increase your power levels.". So they do have various lengths.
The users can change the controls too so the images can't be designed in an image editor.
My question is how do I resize the background so it matches the text.
How would I go around this? The only thing I could think, would be to get the individual size of the font letters and increase it from there but it seems a bad way. Is this the only way or is there another way I could use it? I would prefer not to use GUI.Label
Any ideas?
Thanks
Yes but I don't want the text to shrink or anything, I'de rather fit the sign to the text.
Answer by robertbu · Jul 20, 2014 at 04:25 PM
Getting the exact size of TextMesh is difficult. There are many posts on the issue. But for what you want, I think you can get away with using the renderer.bounds of the TextMesh. While it can be done with a sprite, for this purpose, I recommend you use a Quad instead. A Quad makes the calculations simpler. Just use a shader like Unlit/Texture with your background as the texture. An example:
Create a TextMesh/3D Text object
Set the Anchor to the middle center
Create a Quad game object
Make the Quad a child
Set the Quad position to (0,0,0)
Put your material on the Quad
Attach the following script to the Quad
Drag and drop the Text mesh object in the Hierarchy to the 'tm' variable in the script.
pragma strict
public var tm : TextMesh; public var xScaleFactor : float = 1.1; public var yScaleFactor : float = 1.03;
function Update() { var x = tm.renderer.bounds.size.x xScaleFactor; var y = tm.renderer.bounds.size.y yScaleFactor; transform.localScale = Vector3(x,y,1); }
Note if you want to use a Sprite, you will need to get the Sprite.bounds when the scale is (1,1,1) and then scale based on these values. A Quad makes it easy since the size of a Quad with a scale of (1,1,1) is (1,1,1).
Thank you for your answer! It worked! Just trying to make the texture brighter and make it work for labels with \n in them. Thanks!
Forgot to mention, the code above scales every frame. You may want to modify what you do so that the scale is only recalculated when the string changes.
Your answer
Follow this Question
Related Questions
Render sprite only behind mesh? 0 Answers
2D sprite character movement 3 Answers
Translucent sprites appear solid 0 Answers