4
$\begingroup$

I have a script that creates a new collection but if I run it again it adds a new collection named "Personal Collection.001" and so on, what I would like to tell to the script is that if that collection name is in the scene then don't make a new one.

import bpy

myCol = bpy.data.collections.new('Personal collection')
bpy.context.scene.collection.children.link(myCol) #Creates a new collection


for myCol in bpy.data.collections:
    if myCol.name == "Personal Collection":
        print ("Collection found in scene")

Cheers, Juan

$\endgroup$
2
$\begingroup$

you can do it like this:

import bpy


collectionFound = False

print("START **************")

for myCol in bpy.data.collections:
    print(myCol.name)
    if myCol.name == "Personal Collection":
        collectionFound = True
        print ("Collection found in scene")
        break
        
        
if collectionFound == False:
    myCol = bpy.data.collections.new("Personal Collection")
    bpy.context.scene.collection.children.link(myCol) #Creates a new collection
    print("created")
else:
    print("exists already")

and be careful: you mismatched upper- and lowercase!! String comparison is case sensitive.

$\endgroup$
7
  • 2
    $\begingroup$ collectionFound == False can be "Personal Collection" not in bpy.data.collections. $\endgroup$
    – scurest
    Apr 19 '21 at 15:38
  • $\begingroup$ sorry, i do not understand what do you mean? $\endgroup$
    – Chris
    Apr 19 '21 at 15:41
  • 1
    $\begingroup$ Excellent, thank you so much. Yes you are right about the case, there are so many small things that easily can be overlooked. $\endgroup$ Apr 19 '21 at 15:58
  • $\begingroup$ you are welcome $\endgroup$
    – Chris
    Apr 19 '21 at 16:07
  • 1
    $\begingroup$ @JuanCarlos: to have a cleaner and more safe solution you should use batFingers answer. $\endgroup$
    – Chris
    Apr 19 '21 at 16:42
7
$\begingroup$

Check it exists and is linked to scene.

IMO Two tests required here, one to test if collection exists, and secondly if it is linked at any level to the current scene. A quick test for the latter is to see if the scene is a user of the collection.

import bpy
context = bpy.context

# name of collection
name = "Foo"

scene = context.scene

coll = bpy.data.collections.get(name)
# if it doesn't exist create it
if coll is None:
    coll = bpy.data.collections.new(name)
# if it is not linked to scene colleciton treelink it
if not scene.user_of_id(coll):
    context.collection.children.link(coll)

Related

How to get all collections of the current scene?

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.