Creating sublayers with python

Hi guys. I have a simple python script that creates a few layers with different colors which I think I based on a script I found from Helvetosaur here on the forum (I think). Now I’m wondering how I can create one Main layer and have the 3 layers be created as a sublayer. I’ve been trying this trick with Mainlayer::Sublayer but somehow I couldn’t get it to work. Anybody that could help me out here?

import scriptcontext as sc
import Rhino
import rhinoscriptsyntax as rs

layer = Rhino.DocObjects.Layer()

def AddLayers():
    layernames = ["Layer1", "Layer2", "Layer3"]
    Colors = [(255,0,0), (0,255,0), (0,255,255)]
    Count = 0
    for x in layernames:
        layer.Name = x
        rs.LayerColor(x, Colors[Count])
        Count += 1

@siemen, just use rs.AddLayer which allows to define a parent layer:

import rhinoscriptsyntax as rs

def DoSomething():
    main_layer = rs.AddLayer("Main")
    names = ["Layer1", "Layer2", "Layer3"]
    colors = [(255,0,0), (0,255,0), (0,255,255)]
    for i in xrange(len(names)):
        rs.AddLayer(names[i], colors[i], True, False, main_layer)


1 Like

AddLayer() has some optional arguments including ‘parent’ - which you can use to specify a parent layer if you want a layer to be its sublayer. The parent layer has to exist first.

Thus, create your parent later and then add your sublayers:

import rhinoscriptsyntax as rs

def TestAddSubLayers():
    if not rs.IsLayer(parent_layer): rs.AddLayer(parent_layer)
    sublayernames = ["Layer1", "Layer2", "Layer3"]
    Colors = [(255,0,0), (0,255,0), (0,255,255)]
    for i in range(len(sublayernames)):
        # Color is also directly specifiable


1 Like

Thanks @clement & @Helvetosaur! I’ll try this out.

Just out of curiosity: On that for loop, why do you both use something like “range(len(names))” instead of just “names”? I would think the way I did it is faster (as in, less typing) so I assume there’s a reason why you’re doing it like that?


because we then have an index to access both lists, the one for the layer names and the one for the colors.


Aha! So it replaces my “Count” logic?

@siemen, yes, you could also simplify it using this:

    for name, color in zip(names, colors):
        rs.AddLayer(name, color, True, False, main_layer)


1 Like

Great, thanks a lot!