在 Unity 中的 sprite 上写入文本

Que*_*n3r 4 c# unity-game-engine

我想在 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

每个单元格都附加了这个脚本

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
}
Run Code Online (Sandbox Code Playgroud)

因此,在层次结构中,每个单元格都被添加到“地图”中并获得自己的层次结构

在此输入图像描述

画布设置为“随屏幕大小缩放”,并且文本本身具有这些设置

在此输入图像描述

我只想在这个精灵上写下单元格的值。也许有更干净的方法?

如果有人可以帮助解决这个问题,那就太好了!

Ser*_*kov 5

您将为画布选择渲染模式“世界”。然后设置比例和宽度/高度值。

另外,您还会记得对图层进行排序。如果您不为 UI 使用单独的相机,画布层将比精灵渲染器更大。