Cannot Instantiate to the right position

I have a panel (resized box) and I try to create an 8x4 array of other planes inside of it. I am trying to calculate how to position the whole array at the center of the panel but to no avail.

This is what I’ve tried so far (elementPrefab is the small plane, while the script is attached to the panel):

//the space on the edges of the panel, where the array shouldn't be
var x_extra_space : float = (transform.localScale.x-8*elementPrefab.transform.localScale.x)/2.0;
var y_extra_space : float = (transform.localScale.y-4*elementPrefab.transform.localScale.y)/2.0;
//creating 32 elements and positioning them
for( var i : int = 0; i < 32; i++){
	var curElement : GameObject = Instantiate(elementPrefab,
		Vector3( x_extra_space + (2*(i % 8)+1)*(elementPrefab.transform.localScale.x/2.0) - transform.localScale.x/2.0,
			-y_extra_space-(2*(i / 8)+1)*(elementPrefab.transform.localScale.y/2.0) + transform.localScale.y,
			transform.position.z - elementPrefab.transform.localScale.z),


From my experience with what I’m trying to do, if the position of a child is at (0, 0), then it is right at the center of the parent.

That’s an explanation for better understanding:


This is what I get when I execute the above code (the gray area is the panel, while the planes are clearly visible):


What’s wrong with my code? As I think it, it should work.

I found what you were doing to be somewhat convoluted. In addition, since you are not sizing the ‘elementPrefab’ game objects, you should not care about the extra space. That is, you want to center your 8 x 4 grid on the parent game object, and the extra space will be any space left over. Likewise, your calculations need not use the scale of the parent object. You use ‘transform.localScale’ on lines 7 - 9, which is likely the root of your issues. Here is a quick rewrite:

var elementPrefab : GameObject;

var cols = 8;
var rows = 4;

function Start() {
	var width  = elementPrefab.transform.localScale.x;
	var height = elementPrefab.transform.localScale.y;
	var v3StartPos : Vector3;
	v3StartPos.x = transform.position.x - cols*width / 2.0  + width / 2.0;
	v3StartPos.y = transform.position.y - rows*height / 2.0 + height / 2.0;
	v3StartPos.z = -0.1;
	for( var i : int = 0; i < cols; i++){
		for (var j = 0; j < rows; j++) {
			var curElement : GameObject = Instantiate(elementPrefab);
			curElement.transform.position = Vector3(i * width, j * height, 0.0) + v3StartPos;