0
我想在Unity中創建一個精靈的網格。每個單元應該有一個數字。在Unity中的精靈上寫文本
這是它應該如何看
和我的格子看起來這
於是我產生了細胞,並將它們添加到一個空的遊戲物體稱爲
地圖
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
}
}
}
每個單元有這個附加腳本
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
}
所以在層次結構中,每個單元添加到 「地圖」,並得到了這個自己的層次
的畫布設置爲「Scale with Screensize」並且文字本身具有這些設置
我只是想寫這個精靈的單元格的值。也許有更乾淨的方法?
如果有人能幫助解決這個問題,會不錯!