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)
因此,在层次结构中,每个单元格都被添加到“地图”中并获得自己的层次结构
画布设置为“随屏幕大小缩放”,并且文本本身具有这些设置
我只想在这个精灵上写下单元格的值。也许有更干净的方法?
如果有人可以帮助解决这个问题,那就太好了!
归档时间: |
|
查看次数: |
7691 次 |
最近记录: |