C# - select objects by Layer

Hi,

Firstly, I am still a beginner in C# and still trying to understand how it works.
So, what I am trying to do is to make a script that automatically selects all objects in a specific layer.

private void RunScript(int inLayer, ref object A, ref object B)
{

//select specific layer in rhino doc
Rhino.RhinoDoc doc = Rhino.RhinoDoc.ActiveDoc;
var selLayer = doc.Layers.FindIndex(inLayer);

//get objects in layer
Rhino.DocObjects.RhinoObject[] objs = doc.Objects.FindByLayer(selLayer);

A = selLayer;
B = objs;

}

However, instead of selecting the objects, it just selects the object’s properties ( I guess).

MeshObject: (unnamed) (2065376000)
ExtrusionObject: (unnamed) (0)
ExtrusionObject: (unnamed) (0)

Can someone explain to me why does this happen? and how to solve this?
Thanks!

You must select objects after finding them:

private void RunScript(string layername)
  {
    Rhino.DocObjects.RhinoObject[] rhobjs = doc.Objects.FindByLayer(layername);
    for (int i = 0; i < rhobjs.Length; i++)
      rhobjs[i].Select(true);
  }

Zaqi.gh (12.9 KB)

2 Likes

Hi Mahdiyar,

Thanks for your help! But it still shows these in the output:

BrepObject: (unnamed) (0)
MeshObject: (unnamed) (-2102460576)
BrepObject: (unnamed) (0)
ExtrusionObject: (unnamed) (0)

Would it be possible to reference the geometry instead of the properties in the output?

Thanks,
Z

Sorry for misunderstanding, I thought you want to select them in Rhino Viewport.

Rhino.DocObjects.RhinoObject[] rhobjs = doc.Objects.FindByLayer(layername);
    List<object> ghobjs = new List<object>();
    foreach (Rhino.DocObjects.RhinoObject rhObj in rhobjs)
      ghobjs.Add(rhObj.Geometry);
    A = ghobjs;

Zaqi.gh (12.2 KB)

3 Likes

ahh, great!! super!

Thank you so much for your help!

Best,
Zaqi

Is the a way to select object in sub-layers of that layer too?

var ghobjs = new List<object>();
var selectedLayer = RhinoDoc.ActiveDoc.Layers.FindName(layerName);
var layers = new List<Rhino.DocObjects.Layer>(){selectedLayer};
if(subLayer)
{
  foreach(var layer in RhinoDoc.ActiveDoc.Layers)
    if(layer.IsChildOf(selectedLayer))
      layers.Add(layer);
}
B = layers;
foreach(var layer in layers)
{
  var rhobjs = doc.Objects.FindByLayer(layer);
  foreach (var rhObj in rhobjs)
    ghobjs.Add(rhObj.Geometry);
}
A = ghobjs;

Adnanmakda95.gh (16.1 KB)

3 Likes

Thank you for such a quick response. Works perfectly well. Thank you once again!

I wanted to import a .3dm file with all layers and textures grasshopper. Do you think its possible?

I’m not sure if I understand what you mean by importing. Maybe read3dmFile component from Human plugin could help.