I created a Python like this

bpy.ops.object.move_to_collection(collection_index=2, new_collection_name="Background")

But this code must have a collection called "Background" in the scene from the beginning

I want this.

  1. If there was no collection called "Background", we would create one with Python and move the selected object
  2. If the "Background" collection exists, just move it instead of creating a new one

And I'd like to go from ViewPort to Hide I created this code, but I don't know how to specify the "Background"

bpy.context.scene.hide_viewport = True


With just these two lines, I was able to create Empty if it wasn't there and select it if it was there.



I was putting up the wrong code. bpy.context.scene.exclude = True

When I modified it in this way, I get an error bg_col.hide_exclude = True

  • $\begingroup$ Please ask only one question per post to make Q&A useful to others too. Please read: blender.stackexchange.com/help/how-to-ask $\endgroup$
    – brockmann
    Jul 29, 2020 at 8:04
  • $\begingroup$ Oh, sorry... I'll be more careful next time. Forgive me for just asking this question for a moment... $\endgroup$
    – InamuraJIN
    Jul 29, 2020 at 8:38
  • 2
    $\begingroup$ After trying to code the process, I accidentally found out there is a bunch of condition that should be handle correctly. The process is not that easy when coder is not familiar with the bpy structure. Then this question need to split in several question to make it more general (or module? Atomic question?) to help other reuse this Q&A. $\endgroup$
    – HikariTW
    Jul 29, 2020 at 8:43

1 Answer 1

import bpy

C = bpy.context
D = bpy.data
S = D.scenes["Scene"]

if not D.collections.get("Background"): #Get collection by name in data, and check if None
    bg_col = D.collections.new("Background") # Create a new one if not found
    # Add it to your Scene unless you don't need to see it in your scene
    bg_col = D.collections.get("Background")

bg_col.hide_viewport = True #This is not the eye icon but the monitor icon hidden

  • 1
    $\begingroup$ Can error if background collection is not part of the scene in context. $\endgroup$
    – brockmann
    Jul 29, 2020 at 8:08
  • $\begingroup$ Then the process will be done silently. Not Error but an intentional if Background collection is in other scene....I guess? Not sure if there might be an real Error when dealing with collection not in current scene $\endgroup$
    – HikariTW
    Jul 29, 2020 at 8:48
  • $\begingroup$ I'm sorry! I wrote the wrong code in my questionnaire. I've edited the question. $\endgroup$
    – InamuraJIN
    Jul 29, 2020 at 12:07
  • $\begingroup$ You can save 2 lines with bg_col = D.collections.get("Background") then if bg_col is None: etc. and you don't need the else: $\endgroup$
    – Gorgious
    Feb 1, 2022 at 13:11

You must log in to answer this question.

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