2017-10-07 200 views
0

我想在Unity中創建一個精靈的網格。每個單元應該有一個數字。在Unity中的精靈上寫文本

這是它應該如何看

enter image description here

和我的格子看起來這

enter image description here

於是我產生了細胞,並將它們添加到一個空的遊戲物體稱爲

地圖

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 
} 

所以在層次結構中,每個單元添加到 「地圖」,並得到了這個自己的層次

enter image description here

的畫布設置爲「Scale with Screensize」並且文字本身具有這些設置

enter image description here

我只是想寫這個精靈的單元格的值。也許有更乾淨的方法?

如果有人能幫助解決這個問題,會不錯!

回答

1

您將爲您的畫布選擇渲染模式「世界」。然後設置比例和寬度/高度值。

此外,你會記得有關排序圖層。如果您不使用單獨的相機進行UI,則Canvas圖層將比Sprite渲染器更大。