【问题标题】:Instantiate prefabs in matrix shape UNITY以矩阵形状 UNITY 实例化预制件
【发布时间】:2020-08-16 18:54:53
【问题描述】:

我的问题:我需要实例化 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 等矩阵。 有什么解决办法吗?

【问题讨论】:

  • 你只是想让它们居中而不是左上角?
  • 是的,但我希望它们位于中心并调整大小以适应屏幕。如果我需要实例化 4x4,对象的大小会更大,以便它们之间的距离保持不变。如果我需要实例化 10x10 的正方形应该更小..

标签: c# unity3d matrix instantiation


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 2021-10-27
    • 1970-01-01
    • 2014-08-28
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多