Render text on sprite prefab - 2D iOS

Hello all,

I’d like to ask whether it would be possible to render/draw text dynamically on prefabs.
Specifically, what I would like to do is have planets falling from the top of the screen (that would be generated from a sprite prefab) and on top of each one’s surface to display a different word, which is taken from a JSON file. Additionally I’d like the text to follow the downwards motion of the planet it’s drawn on.
Is this something that would be possible with the free version of Unity? And what would be the workflow for building something like that?

I would hope this could be done via GuiTextures or something, but I haven’t found a way to build it yet or any relevant tutorials. The only alternative I can think of is creating a sprite for each one of the words separately and loading them all to the scene, but I’m afraid this will soon create a mesh.

Any suggestions would really help!
Thank you

The simplest way would be to have a TextMesh that’s a child of the sprite. Use renderer.sortingLayerID and renderer.sortingOrder (in code) to get the text to draw over the sprite as necessary.

To expand on Eric5h5’s answer. You would want to set up a GameObject with a TextMesh component as a child of your Sprite.

And then attach the following script to it:

using UnityEngine;

public class SpriteText : MonoBehaviour
    void Start()
        var parent = transform.parent;

        var parentRenderer = parent.GetComponent<Renderer>();
        var renderer = GetComponent<Renderer>();
        renderer.sortingLayerID = parentRenderer.sortingLayerID;
        renderer.sortingOrder = parentRenderer.sortingOrder;

        var spriteTransform = parent.transform;
        var text = GetComponent<TextMesh>();
        var pos = spriteTransform.position;
        text.text = string.Format("{0}, {1}", pos.x, pos.y);

thanks for the quick reply. Oddly, setting the offset Z to -1, fixed the problem. The -1 is what I find strange. I have no idea why -1 works, just tried a negative number, after trying a few positive ones.

I’m doing a 2D game and needed text to follow a moving Sprite. I just added a GameObject child to the Sprite and added a Text Mesh as a component and changed the Offset Z value to -1 as suggested and all is well. I did not need to do anything with scripting for the mesh. When the sprite move, the text moves.