- Home /
Question by
unity_TDkmLyQfc3QYFQ · May 04, 2020 at 09:55 AM ·
canvasinstantiate prefabmatrix
Instantiate Object to always form a matrix on my screen
I have a square prefab and I want to instantiate NxN prefabs that will form a matrix on the screen.
All the objects are instantiated and are set to have as parent a canvas. My prefab is anchored to the top-left corner to the 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. Is there any solution?
screenshot-2020-05-02-at-113915.png
(50.5 kB)
Comment
Your answer
