0
$\begingroup$

I'm developing a simple addon and I need the ability to create a bunch of custom objects.

I have gotten to a point in which I have a custom UI panel that has an eyedropper which can sample objects from the 3d-viewport.

How can I now create a new object from the selection using Python?

Here's how I'm drawing the panel:

def draw(self,context):
        layout = self.layout
        col = layout.column()
        col.prop_search(context.scene, "backgroundObject", context.scene, "objects", text="Select Background Object")

And here's how I'm trying to use it in the operator:

import bpy

class myOperator(bpy.types.Operator):

    bl_idname = "view3d.my_tool"
    bl_label = "do something"
    bl_description = "description"
    bl_options = {'REGISTER', 'UNDO'}  # Enable undo for the operator.

 
    def execute(self, context):
        #from rna_prop_ui import rna_idprop_ui_prop_get #for the object eyedropper
        bg_obj = context.scene.backgroundObject

        for i in range(20):
            bpy.ops.object.add_named(linked=True, name=str(bg_obj.name), matrix=((0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)), drop_x=0, drop_y=0) #add the background object
               
        return {'FINISHED'} #FINISHED is a special keyword

As you can see, I'm currently trying to use the add_named method but I don't really understand what the matrix is for and I didn't find any documentation on it either. So perhaps this is the wrong approach for what I want.

To summarize: How can I have a custom panel that can select an object with the eyedropper and the create linked copies of that object at specific coordinates?

$\endgroup$

1 Answer 1

1
$\begingroup$

This is how you can do this:

# get the object, in my example it is an active one
# you can use your approach, though:
obj = bpy.context.object

for i in range(20):

    # create new object:
    new = bpy.data.objects.new("name_"+str(i), obj.data)

    # insert the object inside active collection:
    bpy.context.collection.objects.link(new)

    # set a location (shift objects by x)
    new.location = (i,0,0)
$\endgroup$
3
  • $\begingroup$ Thank you so much, that works! Just had to the use str(i) when concatenating the name_ with i $\endgroup$
    – user44109
    Apr 25, 2022 at 13:14
  • $\begingroup$ Yep, I haven't tested it, sorry. $\endgroup$
    – Crantisz
    Apr 25, 2022 at 13:23
  • $\begingroup$ @Gorgious woops that len is a typo, will fix $\endgroup$
    – user44109
    Apr 26, 2022 at 19:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .