# Position object in top left of Rect Transform 2D

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

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).

• Is there any reason why you don't use Unity's grid system? Commented Jun 30, 2022 at 20:33
• @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 Commented Jun 30, 2022 at 20:36
• Then I suggest you learn it. It's relevantly easy to learn and work with, both visually and via code Commented Jul 1, 2022 at 1:34

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


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


rectTransform = GetComponent<RectTransform>();