我想在 Unity 中创建一个带有 Sprite 的网格。每个单元格上都应该有一个数字。
这是它应该看起来的样子
我的网格看起来像这样
所以我生成单元格并将它们添加到一个名为的空游戏对象
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
}
}
}
每个单元格都附加了这个脚本
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
}
所以在层次结构中,每个单元格都被添加到“ map ”中并获得了这个自己的层次结构
Canvas 设置为“按屏幕大小缩放”,文本本身具有这些设置
我只想在这个 Sprite 上写出单元格的值。也许有更干净的方法?
如果有人可以帮助解决这个问题会很好!
最佳答案
您将为 Canvas 选择渲染模式“世界”。然后设置比例和宽度/高度值。
此外,您还会记得对图层进行排序。如果您不为 UI 使用单独的相机, Canvas 层将比 Sprite 渲染器大。
关于c# - 在 Unity 中在 Sprite 上写文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619658/