How I can use preselected objects in scripts?

How I can make the following code to work with multiple preselected objects instead to ask-me to select an object?

obj = rs.GetObject("Select object")
if obj:
    rs.SetUserText( obj, "Key1", "0" )
    rs.SetUserText( obj, "Key2", "0" )

Best regards.

Hi @Cumberland
Pretty sure there is a smarter way but here you go :

import Rhino
import scriptcontext as sc

# Get all selected objects (preselected in the document)
objects = sc.doc.Objects.GetSelectedObjects(False, False)

# If no objects are selected, you can ask the user to select one (optional)
if not objects:
    obj = Rhino.Input.RhinoGet.GetObject("Select an object", False, Rhino.DocObjects.ObjectType.AnyObject)
    if obj:
        objects = [obj]
if objects:
    for obj in objects:
        obj.Attributes.SetUserString("Key1", "0")
        obj.Attributes.SetUserString("Key2", "0")
        obj.CommitChanges() 
else:
    print("No objects selected.")

Hope this sparks some ideas,
Farouk

1 Like

Thank you. Works good.

Smarter, I don’t know, easier and less code maybe:

obj_ids=rs.SelectObjects("Select some objects", preselect=True)

If objects are preselected, the script will continue with those. If nothing it preselected, you will get the prompt to select some objects.

2 Likes