c# - 在 Unity 中在 Sprite 上写文本

标签 c# unity3d

我想在 Unity 中创建一个带有 Sprite 的网格。每个单元格上都应该有一个数字。

这是它应该看起来的样子

enter image description here

我的网格看起来像这样

enter image description here

所以我生成单元格并将它们添加到一个名为的空游戏对象

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 ”中并获得了这个自己的层次结构

enter image description here

Canvas 设置为“按屏幕大小缩放”,文本本身具有这些设置

enter image description here

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

如果有人可以帮助解决这个问题会很好!

最佳答案

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

此外,您还会记得对图层进行排序。如果您不为 UI 使用单独的相机, Canvas 层将比 Sprite 渲染器大。

关于c# - 在 Unity 中在 Sprite 上写文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619658/

相关文章:

c# - 用于最后操作的轮换列表的集合是什么?

c# - ExpressionTreeVisitor 中 ConstantExpression 的部分求值

c# - Caliburn.微单元测试

c# - UWP 后台任务未执行

c# - Unity 3D "automatic"嘴唇同步?

c# - Unity3d-播放和暂停之间的过渡时声音粗糙

unity3d - 如何在 Unity 中正确创建无效的 Vector3?

c# - NAudio 一起播放多个声音给出异常 "All mixer inputs must have the same WaveFormat"

c# - Rendertexture 减慢统一?

unity3d - 线框着色器 : How to display quads and not triangles?