1

I am doing some basic Python in Blender and I want to add in a grid of cubes. If you can imagine that as count is 5 this creates a 5x5 grid of 25 cubes. However, I've got the code working so that the x axis increases each time but don't know how to edit the nested for loop so it does the same and increases along the y, as at the moment all that happens is you get a 5-long line of cubes with 5 more cubes layered on top of it.

#how many cubes you want to add on each axis
count = 5

for i in range (0,count):
    for cube_instance in range(0,count):
        x = 1
        y = 1
        z = 0
        bpy.ops.mesh.primitive_cube_add(location=(x * cube_instance + 1,y,z))

Thanks for any help.

Charlie
  • 230
  • 1
  • 9
  • Why do you keep re-defining the variables for each iteration of each loop? – zondo Apr 23 '17 at 14:46
  • As in using cube_instance instead of i? Just helps me to distinguish between them. – Charlie Apr 23 '17 at 16:59
  • No. What I mean is that each `i` runs the inner loop. In that loop, you then assign `x` to `1`, `y` to `1`, and `z` to 0. Therefore, for a count of 5, `x` is assigned to `1` 5*5=25 times, and the same happens for `y` and `z`. Since they are always being assigned to the same thing, you might as well put all those definitions outside of the loops. Apparently, `i` should actually be in the loop (per zipa's answer), but it doesn't need to be in the inner loop, just the outer one. – zondo Apr 23 '17 at 20:31
  • I get you. Yeah, they could be outside of the loops, there's no reason for them to be inside the loop. – Charlie Apr 23 '17 at 20:37
  • Except y as y needs to be redefined. – Charlie Apr 23 '17 at 20:38
  • It depends only on `i`. Since `i` does not change for the inner loop, you can put it just in the outer loop like this: `for i in range(count): y = i + 1; for cube_instance in range(count): ...` – zondo Apr 23 '17 at 20:39

1 Answers1

4

I'm guessing y = 1 + i should do the trick.

zipa
  • 27,316
  • 6
  • 40
  • 58
  • Haha thanks dude :) Yep works a treat now, I'm working towards developing a Minecraft style game as programming experience. – Charlie Apr 23 '17 at 14:00