Saturday, April 4, 2015

Sprite with Text in Unity3D

I am working on one game where I wanted to show text over sprite. With new Unity UI System, it's quite easy to create button as sprite and text over it.

But if you want to create a traditional sprite and add text to it, this post describes the same.

Basic idea is to add 3D text component to sprite, but if you have tried it then you might know after adding 3D text component we need to move it to same sorting order as sprite. Also we need to layout text properly to set alignment.

Before we begin, I assume you know how to create Sprite, how to create 3D text component and make it a Prefab object. If not you can refer this article to know how to make Prefab object.

Finally, following is my script which I attached to Sprite. Once added to Sprite, It will create 3D text component from provided Prefab object and add the same to Sprite.
using UnityEngine;
using System.Collections;
public class TextScript : MonoBehaviour {
 public string text;
 public GameObject textPrefab;
 void Start() {
  GameObject text = Instantiate(textPrefab) as GameObject;
  text.transform.parent = gameObject.transform;
  text.transform.rotation = gameObject.transform.rotation;

  TextMesh textInstance = text.GetComponent();
  textInstance.text = text;

  Renderer textRenderer = text.GetComponent ();
  Renderer thisRenderer = GetComponent ();

  textRenderer.sortingLayerID = thisRenderer.sortingLayerID;
  textRenderer.sortingOrder = thisRenderer.sortingOrder+1;
  Bounds textBounds = textRenderer.bounds;
  Bounds parentBounds = thisRenderer.bounds;
  float x = gameObject.transform.position.x 
                     - (textBounds.size.x/2); 
  float y = gameObject.transform.position.y 
                     + (textBounds.size.y/2);
  textInstance.transform.position = 
                     new Vector3(x, y, + 1);
That's it, you can add this script to any component and add text over it.

No comments:

Post a Comment