Reputation: 3752
I want to create a grid with sprites in Unity. Each cell should have a number on it.
This is how it should look
and my grid looks this
So I generate the cells and add them to a empty gameobject called
Map
private GameObject cellPrefab;
private const int CELL_COUNT_X = 10; // create 100 cells
private const int CELL_COUNT_Y = 10;
private const float CELL_SPACING = 1.1f; // with a small spacing
private List<Cell> cells = new List<Cell>(); // store all cells here
private const int NUM_RANGE_MIN = 1; // cell value range
private const int NUM_RANGE_MAX = 10;
private void Start()
{
cellPrefab = Resources.Load(StringCollection.CELL) as GameObject;
for (int x = 0; x < CELL_COUNT_X; x++)
{
for (int y = 0; y < CELL_COUNT_Y; y++)
{
float spawnPosX = x * CELL_SPACING - CELL_COUNT_X / 2;
float spawnPosY = y * CELL_SPACING - CELL_COUNT_Y / 2;
GameObject cell = Instantiate(cellPrefab, new Vector2(spawnPosX, spawnPosY), cellPrefab.transform.rotation); // create the new cell
cell.transform.SetParent(transform); // add the cell to the map
Cell cellComponent = cell.GetComponent<Cell>();
cellComponent.InitCell(Random.Range(NUM_RANGE_MIN, NUM_RANGE_MAX)); // init the cell value
cells.Add(cellComponent); // add to list
}
}
}
Each cell got this script attached
private Text txtCellValue;
private int cellValue;
public void InitCell(int value)
{
txtCellValue = transform.GetChild(0).GetChild(0).GetComponent<Text>(); // get the text component of the cell
cellValue = value; // set the value
txtCellValue.text = cellValue.ToString(); // update the GUI
}
So in the hierarchy, each cell is added to the "Map" and got this own hierarchy
The canvas is set on "Scale with Screensize" and the text itself has these settings
I just want to write the value of the cell on this sprite. Maybe there is a more clean way?
Would be nice if someone could help fixing this!
Upvotes: 4
Views: 7781
Reputation: 540
You will select render mode "world" for your canvas. Then set the scale and width/height values.
Also, you will remember about sorting layers. Canvas layer would be bigger than sprite renderer, if you dont use separate camera for UI.
Upvotes: 5