Retrieve Tag Name of Selected Object

I spent the last few late evenings when I should have gone to bed trying to work this out.

I’m trying to retrieve the tag name of a selected object.

I’ve checked out ruby.sketchup and done many Forum / Google searches…

Tag is still called as Layer in Ruby API…

References:

#Dirty code snippet:

def get_tag_name
  model = Sketchup.active_model
  selection = model.selection
  if selection.single_object?
    if selection.first.respond_to?(:layer)
      object = selection.first
      layer = object.layer
      layer_name = Sketchup.version.to_i < 20 ? layer.name : layer.display_name
      UI.messagebox("#{layer_name} is associated to selected object #{object.class} ")
    else
      UI.messagebox("Selected object has no Layer/Tag name .")
    end
  else
    UI.messagebox("Select exactly one object")
  end
  layer_name
end
get_tag_name

EDIT: #display_name added for SU version > 2020

1 Like

thanks dezmo

correct me if I’m wrong, essentially…

model = Sketchup.active_model
selection = model.selection
object = selection.first
layer = object.layer
layer_name = layer.name

is retrieving the tag name which was what I have been trying to work with but just couldn’t get it right.

Yes.
As you can see in my previous post as well… but here are the proof:

As of SketchUp 2020 “Layers” were renamed to “Tags” in the UI. The API retains the use of “Layer” for compatibility and is synonymous with “Tag”.

https://ruby.sketchup.com/Sketchup/Layer.html


BTW. Again, for compatibility reason, they implemented a method In SU2020:
The #display_name method is used to retrieve the display name of the layer.

(implemented to my first response)

was using the layer class but trying to get something out of layer.name was eluding me :scream:

Actually a one liner:

Sketchup.active_model.selection.first.layer.name

But This will return “Layer0” for “Untagged” in SU 2020 or later

Therefore:

# if you are using SU 2020 or later
Sketchup.active_model.selection.first.layer.display_name

Will give you the proper name as in the UI. But you will get an error in earlier SU versions.