Creating sublayers with python


#1

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
        sc.doc.Layers.Add(layer)
        rs.LayerColor(x, Colors[Count])
        Count += 1
AddLayers()

#2

@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)
    
DoSomething()

_
c.


#3

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():
    parent_layer="MainLayer"
    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
        rs.AddLayer(sublayernames[i],color=Colors[i],parent=parent_layer)
TestAddSubLayers()

–Mitch


#4

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


#5

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?


#6

@siemen,

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

_
c.


#7

Aha! So it replaces my “Count” logic?


#8

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

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

_
c.


#9

Great, thanks a lot!