0
\$\begingroup\$

I have a GameObject with a Rect Transform (I assume I should be using one) and I am trying to essentially spawn squares in a grid formation. However it starts from the middle and I want it to start from the top left.

I have tried adjusting the pivot but it seems to have no affect so I am pretty stuck.

Here is an image of what I have and the Rect Transform

Image of editor

Here is a snippet of my code for performing the Instantiation

rectTransform = GetComponent<RectTransform>();
Vector3 position = new Vector3(x * 1, y * -1, 0);
GameObject newPiece = Instantiate(PiecePrefabs[(int)type], position, Quaternion.identity);
newPiece.transform.SetParent(rectTransform);

I want this to start at the top left of the rect transform. (Assuming I should be using one).

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Is there any reason why you don't use Unity's grid system? \$\endgroup\$
    – Arian_ki
    Jun 30, 2022 at 20:33
  • \$\begingroup\$ @Arian_ki No reason. I could look at it in fact. I'm pretty new to Unity but I have experience with writing my own engines \$\endgroup\$
    – Emobe
    Jun 30, 2022 at 20:36
  • 1
    \$\begingroup\$ Then I suggest you learn it. It's relevantly easy to learn and work with, both visually and via code \$\endgroup\$
    – Arian_ki
    Jul 1, 2022 at 1:34

2 Answers 2

0
\$\begingroup\$

You can get the absolute position of the corner by

firstPosition = new Vector3(
    rectTransform.position - rectTransform.width / 2f,
    rectTransform.position + rectTransform.height / 2f,
    0f);
Instantiate(prefab, firstPosition, Quaternion.identity, rectTransform);

for (columns) {
    for (rows) {
        var position = new Vector3(
            firstPosition.x + columns * prefabWidth,
            firstPosition.y - rows * prefabHeight,
            0f);
        Instantiate(prefab, position, Quaternion.identity, rectTransform);
    }
}
\$\endgroup\$
0
\$\begingroup\$

While you can position it at the corner, personally I think its much easier to just add an offset, you can modify it in the inspector easily and change it through code whenever you like. It only takes a couple lines to do.

First create an offset variable that you can modify in the inspector:

public Vector2 spawnOffset = new(-50, 50);

Then add it to your spawn position:

rectTransform = GetComponent<RectTransform>();
Vector3 position = new Vector3(x * 1, y * -1, 0);
position += spawnOffset;
GameObject newPiece = Instantiate(PiecePrefabs[(int)type], position, Quaternion.identity);
newPiece.transform.SetParent(rectTransform);

Of course, you can get the position of the top corner, but in my personal opinion, this is way easier and more customizable.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .