[英]Instantiate prefabs in matrix shape UNITY
我的問題:我需要實例化 NxN 預制件以在屏幕上形成矩陣。 我的解決方案:
所有對象都被實例化並設置為具有 canvas 作為父對象。 我的預制件固定在 canvas 的左上角。 我目前不滿足我需要的解決方案是:
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;
}
偽代碼測量 canvas 的總寬度 為元素之間的間距指定一個百分比 將元素大小設置為 #of 個元素/(畫布寬度 - 間距) 在 i 或 j 的每次迭代中創建一個 for 循環 將下一個 ui 元素向上或向下移動元素大小+(百分比空間/元素個數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.