2
$\begingroup$

I made this short script. Why is the new object being added to the default collection? Can I get around unlinking the object, not linking it in the first place? How do you add an object only to a specific collection in python?

if (bpy.data.collections.find('Tiles') == True):
    tiles_collection = bpy.data.collections['Tiles']
else:
    tiles_collection = bpy.data.collections.new('Tiles')
    bpy.context.scene.collection.children.link(tiles_collection)

bpy.ops.mesh.primitive_plane_add(location=(1, -5, 0), size=1)

basemesh = bpy.context.object

tiles_collection.objects.link(basemesh)

bpy.data.collections['Collection'].objects.unlink(basemesh)

This is what the outliner looks like without the last line in the script:

enter image description here

$\endgroup$
3
  • $\begingroup$ I read your question many times, and failed to understand what are you trying to achieve, please re-organize your question in a clearer way, state clearly what is the result you're getting now, and what is the result you're wishing to achieve. $\endgroup$
    – Georges D
    Oct 31, 2019 at 15:55
  • $\begingroup$ i hope that made it clearer $\endgroup$
    – BK.
    Oct 31, 2019 at 16:30
  • $\begingroup$ I tried to make a question out of it. $\endgroup$
    – BK.
    Oct 31, 2019 at 18:25

1 Answer 1

4
$\begingroup$

bpy.ops.mesh.primitive_plane_add ...

... is doing stuff behind your back, based on the current context. It's creating the mesh, then an object from it, and linking it to the context's active collection. So when you call link, it's linking for the second time.

You could make the 'Tiles' collection active, and let bpy.ops.mesh.primitive_plane_add do its own thing in there...

import bpy

C = bpy.context
D = bpy.data


if D.collections.get('Tiles'):
    tiles_collection = D.collections['Tiles']
else:
    tiles_collection = D.collections.new('Tiles')
    C.scene.collection.children.link(tiles_collection)

C.view_layer.active_layer_collection = \
C.view_layer.layer_collection.children['Tiles']

bpy.ops.mesh.primitive_plane_add(location=(1, -5, 0), size=1)

... I'm not saying it's a great thing to do, that would take someone with more experience than me. It may be better not to call bpy.ops.xxx at all, to avoid context connected activity, or the way you're doing it now may be just fine.

$\endgroup$
1
  • $\begingroup$ thanks for the clarification! $\endgroup$
    – BK.
    Oct 31, 2019 at 22:50

You must log in to answer this question.

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