Stop API calls from creating duplicate Materials

I am just learning Ruby (cough cough) and just doing the basics and already hit a wall. I am just trying to add new materials using ruby but I keep getting duplicate materials just with the added 1,2, etc…) is there a way to look and see if the material exists and skip that one?

Get a handle to all the materials in the current model.

model = Sketchup.active_model
materials = model.materials
material = materials.add(‘Joe’)

# if it exists materials['Joe'] will be used 
# if not the || is a fallback to create it ...
material = materials['Joe'] || materials.add('Joe')



Cover your cough and stay home :wink:

… take advantage of the learning lists …

Also please Read how to post code blocks in the forum …

Lastly there is a specific Ruby subcategory for SketchUp Ruby coding …

… (I’ve reassigned your topic.)

P.S. - Changed “Ruby” in topic title to “API calls” as it isn’t Ruby that creates duplicate material objects, it is the SketchUp core that does this to ensure unique material names, because of the way you were coding.

1 Like

Thank you john that was it. I now need to assign a color and also skip that if it exist lol. but you pointed me in the right direction