实例化为矩阵形状的预制件

问题描述 投票:0回答:1

我的问题:我需要实例化NxN个预制件,以在屏幕上形成矩阵。我的解决方案:

所有对象都被实例化,并设置为具有父画布。我的预制件固定在画布的左上角。我当前无法满足我需要的解决方案是:

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;
        }

但是我希望我的对象之间具有相同的距离,即使我必须生成4x4、6x6、8x8等矩阵。enter image description here有什么解决办法吗?

c# unity3d matrix instantiation
1个回答
0
投票

伪代码测量画布的总宽度为元素之间的间距指定一个百分比将元素大小设置为#of元素/(画布宽度-间距)在i或j的每次迭代中创建一个for循环,将下一个ui元素上下移动一个元素大小+(百分比空间/数字元素)

© www.soinside.com 2019 - 2024. All rights reserved.