Assign materials to layers with identical names

Can anyone help me writing a simple scipt that assigns materials to layers with the same name?

To be clear, the material already exists.

Any help greatly appreciated

Hi @benjamin,

So you have a file with a number of named materials. Do you already have the layers created? Any additional details you can provide might be helpful.

Have you started a script? Can you post your code that isn’t working correctly?

You might also consider posting a sample 3dm file.

– Dale

Hi @benjamin, below is a simple one based on your description:

import Rhino
import scriptcontext

def AssignRenderMaterialToLayers():
    
    layer_names = ["cupboard"]
    material_name = "Cherry"
    
    data = scriptcontext.doc.RenderMaterials.GetEnumerator()
    mats = filter(lambda rm: rm.Name == material_name, data)
    if not mats:
        print "Material '{}' not found".format(material_name) 
        return 
    
    for layer in scriptcontext.doc.Layers:
        if layer.Name in layer_names:
            layer.RenderMaterial = mats[0]

AssignRenderMaterialToLayers()

The script assigns one existing material named “Cherry” to all layers named “cupboard”. You can add multiple layer names to the list at the top, eg.

layer_names = ["cupboard", "cabinet", "wardrobe"]

_
c.

1 Like

Thanks clement!

Is there any way of assigning according to an existing list of materials?

To put it another way: the script lists all materials, then checks if there is an identically named layer, and assigns the material to the layer accordingly (if the material doesn’t have a corresponding layer then it skips it)

Any help greatly appreciated

B

Hi @benjamin, try below:

import Rhino
import scriptcontext

def AssignRenderMaterialToLayers():
    
    render_materials = list(scriptcontext.doc.RenderMaterials)
    if not render_materials: print "0 Materials found !"; return
    
    data = dict()
    for rm in render_materials: data[rm.Name] = rm 
    
    for layer in scriptcontext.doc.Layers:
        if layer.Name in data:
            layer.RenderMaterial = data[layer.Name]

AssignRenderMaterialToLayers()

_
c.

1 Like

Excellent - thank you! A nice little time saver :pray: