How can I add a text centered inside a square Sprite?

Hi,

complete beginner.
I want to create a pretty simple prefab.

It’s called a “pixel” and it’s just that. A square sprite and inside it I want a Number as text centered inside it. Then I want to create a Prefab out of that and instantiate many of that (and also want to change the number inside each of it with code).

But I can’t find a way to create the text inside the square. I tried with UI - Text (Text Mesh Pro). This adds automatically a canvas. After playing around with it a bit I managed to add the number centered in my square. But then when I instantiate many of these the number always stays at the center of the camera view. So I think there is always only one canvas on the screen, but I need to store a number in each “pixel”.

I also tried the “Text” Component on the Square Sprite. But that doesn’t display anything on the square (I made sure to set a color that differentiates itself from the bg color of the square. )

What is the correct way to achieve this?
I want to recreate the game “Coloring Pixels” if you know that.

Thank you Geralt

Text and TextMeshProUGUI both require canvases.

TextMesh and TextMeshPro do not require canvases.

In all cases, adding this by code is really hard. Do it in the editor and then fill out the data at runtime.

Once you have it displayed, you may need to consider layering / sorting orders:

Three (3) ways that Unity draws / stacks / sorts / layers / overlays stuff:

In short,

  1. The default 3D Renderers draw stuff according to Z depth - distance from camera.

  2. SpriteRenderers draw according to their Sorting Layer and Sorting Depth properties

  3. UI Canvas Renderers draw in linear transform sequence, like a stack of papers

If you find that you need to mix and match items using these different ways of rendering, and have them appear in ways they are not initially designed for, you need to:

  • identify what you are using
  • search online for the combination of things you are doing and how to to achieve what you want.

There may be more than one solution to try.

Additional reading in the official docs: