2017-10-07 205 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渲染器更大。