简体   繁体   English

以矩阵形状 UNITY 实例化预制件

[英]Instantiate prefabs in matrix shape UNITY

My problem: I need to instantiate NxN prefabs to form a matrix on the screen.我的问题:我需要实例化 NxN 预制件以在屏幕上形成矩阵。 My solution:我的解决方案:

All the objects are instantiated and are set to have as parent a canvas.所有对象都被实例化并设置为具有 canvas 作为父对象。 My prefab is anchored to the top-left corner to the canvas.我的预制件固定在 canvas 的左上角。 My current solution that does not satisfy my need is:我目前不满足我需要的解决方案是:

int yAnchorPos = -100;
        for (int row = 0; row < nBoardSize; ++row)
        {
            int xAnchorPos = 100;
            _mGameBoard[row] = new GameObject[nBoardSize];
            for (int col = 0; col < nBoardSize; ++col)
            {
                _tilePrefab = Instantiate(_tilePrefab, transform.position, Quaternion.identity);
                _tilePrefab.transform.SetParent(this.transform);
                _tilePrefab.GetComponent<RectTransform>().anchoredPosition = new Vector3(xAnchorPos,yAnchorPos,0);
                _tilePrefab.transform.tag = row.ToString() + col.ToString();
                _tilePrefab.transform.name = _tilePrefab.transform.tag;
                _mGameBoard[row][col] = _tilePrefab;
                _mGameBoard[row][col].GetComponent<Image>().color = colors[UnityEngine.Random.Range(0, 4)];
                xAnchorPos += 150;
            }
            yAnchorPos -= 150;
        }

But I would like my objects to have same distance between them even is I have to generate a matrix of 4x4, 6x6, 8x8, etc.但我希望我的对象之间有相同的距离,即使我必须生成一个 4x4、6x6、8x8 等矩阵。 在此处输入图像描述 Is there any solution?有什么解决办法吗?

psuedo code measure total width of canvas dedicate a percentage to spacing between elements set element size as #of elements / (canvas width - spacing) make a for loop in each iteration of i or j move the next ui element over or down by element size + (percent space / numelements)伪代码测量 canvas 的总宽度 为元素之间的间距指定一个百分比 将元素大小设置为 #of 个元素/(画布宽度 - 间距) 在 i 或 j 的每次迭代中创建一个 for 循环 将下一个 ui 元素向上或向下移动元素大小+(百分比空间/元素个数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM