How does sketchup handle groups and entities in a while loop

How do you create a group of lines from a while loop and how do entities and groups work in Sketchup/Ruby? I can not seem to make this work:

mod = Sketchup.active_model # Open model
ent = mod.entities # All entities in model
sel = mod.selection # Current selection

i = 0 # initiation
num = 10 # iterations

while i < num do
pti = [i,i*i,0] # create first point
i += 1 # go to next
ptj = [i,i*i,0] # create second point
ent.add_line(pti,ptj) # connect
grp = ent.add_group # add to group
end

ent = grp.entities

I have tried inserting the following inside, before and after the while loop. It only worked when it was inside the loop, but then it created a group for each iteration.

grp = ent.add_group
ent = grp.entities

I saw another Topic that said: Create the empty group first and then add entities to the group. However, I do not quite understand how to implement that into my code.

mod = Sketchup.active_model # reference model
ent = mod.entities # All entities in model

i = 0 # initiation
num = 10 # iterations

grp = ent.add_group # add a group
gents = grp.entities
cpt = gents.add_cpoint(ORIGIN)

while i < num do
  pti = [i, i*i, 0] # create first point
  i = i + 1 # go to next
  ptj = [i, i*i, 0] # create second point
  gents.add_line(pti, ptj) # connect
end

cpt.erase!
1 Like

Or …

mod = Sketchup.active_model # reference model
ent = mod.entities # All entities in model

num = 10 # iterations

grp = ent.add_group # add a group
gents = grp.entities
cpt = gents.add_cpoint(ORIGIN)

num.times do |i|
  pti = [i, i*i, 0] # create first point
  j = i + 1 # go to next
  ptj = [j, j*j, 0] # create second point
  gents.add_line(pti, ptj) # connect
end

cpt.erase!

Or for the iteration …

for i in 0...num # ... excludes the last value from the Range
  pti = [i, i*i, 0] # create first point
  j = i + 1 # go to next
  ptj = [j, j*j, 0] # create second point
  gents.add_line(pti, ptj) # connect
end
1 Like

Thank you, it worked by simply naming the entities gents and adding the line to that entity. I guess I shouldn’t have used “ent” twice. So that:

grp = ent.add_group
gents = grp.entities

while i < num do
pti = [i,i*i,0]
i += 1
ptj = [i,i*i,0]
gents.add_line(pti,ptj)
end

It is actually on purpose that I used i += 1 and not j, as I want the iteration to stop after 10 iterations. I am not sure what the .add_cpoint and .erase! does in this case.

I know it was a booboo. (I removed that. It only applied to the 2nd and 3rd examples.)

If you have computations that take time, SketchUp’s engine will delete empty group definitions.
So it’s good practice to insert a temporary cpoint at the group’s origin and then delete it later if it will not be needed.

1 Like