Delete some definition

Hello every-one,
I have some probleme with SketchUp function and find some help pleaz :slight_smile:
I have to update my component with newest but for some reason i cant use classic methode. So i try to erase all of component and insert them with the same transofrmation.
The only problem is that i cant erase the definition, i use many methods and I finish with this :

i=0
j=0
t={}
ents = {}

   definition.instances.each{|component|
   t[i] = component.transformation
   ents[i] = component.parent.entities
   i=i+1
   # component.erase!
   }

definition.entities.erase_entities(definition.entities.to_a)
# definitions.purge_unused

   newDef = model.definitions.load(pathComponent)
   while j<i do
        ents[j].add_instance(newDef, t[j])
        j=j+1
   end
model.commit_operation

" definition.entities.erase_entities(definition.entities.to_a)" or “definitions.purge_unused” both of this function doesnt work. I use this on loop and for a reason that I cant understand the loop stop randomly. (after 4, 15 or 7 iteration)
This probleme make my cry if someone can help that would be very nice :slight_smile:

Have good nay every-one

You say you “use this on loop”, but didn’t show the loop. If you are deleting inside a loop over the same collection as owns the deleted entities, you are creating a “fence post error”. Most collection structures break if you delete one of their members while iterating over the collection. They then stop at a seemingly random place part way through. The answer is to make a separate Array from the collection and to iterate over that Array. Since you are deleting from the original collection, not the Array, the deletion doesn’t break the iterator.

As a side question, why are t and ents created as Hash objects when you then index them with integer i? An Array would suffice and probably perform better.

If you want to update a definition from an external SKP consider this approach…

tdir = Sketchup.temp_dir # >=v2014
model = Sketchup.active_model
defns = model.definitions
name = 'some_name' # set to suit ?
path = 'some_path_to_skp' # replacement skp
tpath = File_join(tdir, name+rand.to_s+'.skp')
tname = defns.unique_name(name)
defn = defns[name]
# bale out unless defn exists
# start operation
model.start_operation("#{name} Update", true)
  tskp = defn.save_as(tpath) # break old connections
  File.delete(tskp)
  ndefn = defns.load(path) # set 'path' to replacement skp earlier
  defn.name = defn.name+rand.to_s # rename
  ndefn.name = name # use original name
  defn.instances.each{|i| i.definition = ndefn }
  defn.entities.clear!
model.commit_operation # removes unused defn

EDIT: Fixed instance update !

Thanks every-one i try this with a new array of definition.name and I loop on this array to delete. It’s work.
I made a mistake and change the hash to array thanks for notice that :smiley:
Thanks again

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.