5

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

batFINGER
  • 84,216
  • 10
  • 108
  • 233
Juan Carlos
  • 179
  • 2
  • 9

2 Answers2

11

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?

batFINGER
  • 84,216
  • 10
  • 108
  • 233
2

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.

Chris
  • 59,454
  • 6
  • 30
  • 84