Requesting help for nested "for loops" to create cubes.

Hi everyone,

I just started taking a class on unity, I apologize if I’m really noob at this. I’ve done some programming here and there, but my major doesn’t really require us to take that many classes on programming like computer science majors.

So here’s my problem.

We need to create a javascript that will generate boxes in some specific way, like so: * will represent a cube

----**
—****
–******
-********


However after many hours of trying to figure this out, I’m stuck with this:

**





We’re suppose to modify our professors code in order to produce the pyramid.

Here’s my code:

var myBox: Transform;
function Start () {
	for (var i = 1; i<=10-i; i++) {
	    for (var j = 10; j>=(i*2)-1; j--) {
	         var xpos = i * 10;       
	         var zpos = j * 10; 
	         var instanceObj = Instantiate (myBox, Vector3(xpos, 50, zpos), Quaternion.identity);
	   }
	}
}

What am I doing wrong and how can I make it right?

Thank you

You’re always starting j at 10, so the zpos will always be 100, resulting in the right-triangle shape you’ve seen. To get a pyramid, you need to change the start for j as well as the end.

Also, why are you using “i <= 10-i” instead of just “i <= 5”?

I tried changing j’s start and end point but nothing really changes other than the side it’s aligned too.

I’m having trouble wrapping my head around this, would you happen to have an idea what do put for j?

Would anyone else know how to do this?

You need to offset zpos by an amount related to I (row index).

The bottom row is offset by zero, the next up is offset by one (cube), the next by two, etc.

If you know the maximum row is “maxRow”, then:

zpos = j * 10 + (maxRow - i) * 10

Then if (i==maxRow) there’s no offset; if (i==maxRow-1) there’s a single offset, etc.

Based on your example with five rows, on row one you have (5-1=4) cubes offset, on row two you have (5-2=3) cubes offset.

It’s helpful (to me) to associativize or whatever that:

zpos = ( j + (maxRow - i) ) * 10;

Then you can see you’re putting a block at the “logical position” of (j+maxrow-i), then to get the block to the right “real position” you’re scaling by ten.

Ahhhh thank you so much. I get it now that you brought up about the offset. I got it working! TY!