Unity 4.3 - Draw Text on Sprite

I’m trying to make a really simple gui system for a new 2d game I’m working on (built in the new unity 4.3). My idea would be to have a button background image, and over the top, write a text label. What is the easiest way to go about this?

2 Answers

2

I’ve done it before.

Simply create a sprite with the background, and create a 3d text object. Give the 3d text object a scale of (0.1,0.1,0.1), and font size of say 28 (leave the scale, play with the font size as much as you need).

Then drag the 3d text object into the background sprite so that it becomes it’s child in the hierarchy, and then set the position of the 3d text to be (0, 0, -2).

There you have a button with text. Now attach a box collider 2d to the sprite, and add a script that has a reference to the TextMesh, and that handles click events:

public class ButtonScript : MonoBehaviour {
    public TextMesh buttonText;

    public void Start() {
        // set the button text
        buttonText.text = "Click here!";
    }

    public void OnMouseUpAsButton() {
        // what happens when mouse is clicked
    }
}

Last thing you have to do is drag the button text into the ‘Button Text’ field of the script in the inspector to create the reference.

Thanks a bunch!

what can i do if i want to make things like: sprite, text, sprite, text? if i have one object with a text moving in front of another object with text, i can see the text through... how can i fix that?

This is nice way to draw text, but for me it does not work correctly with sorting layers. If background sprite have sorting layer above than "default", text is not displayed regardless of its Z coordinate. Of course I want my gui on the top layer, so this causes problem. Anyone knows how to use 3D Text with sorting layers?

Here is the solution and explanation to @mexey question wich is realted to the OP question in that specific case:

Cheers