4
$\begingroup$

For an if statement, I want to check if my current object is in collection 'coll' Here's what I have so far:

def GO():
    objects = bpy.data.objects
    for obj in objects:
        if obj.parent==None and obj.type=='MESH' and obj.collection.name('coll'):
$\endgroup$

2 Answers 2

3
$\begingroup$

Assuming your object is in only one collection, you can use:

if obj.users_collection[0].name == "coll":
    print("yes")

If your object is present in multiple collections and you want to just check if it is also part of the collection named "coll", you can use:

if "coll" in [c.name for c in obj.users_collection]:
    print("yes")
$\endgroup$
3
  • $\begingroup$ I suppose you mean to compare against .name in the first snippet, I suggested an edit. $\endgroup$
    – Ray
    Nov 28, 2023 at 11:45
  • 1
    $\begingroup$ @Ray interesting because I always test my posted code. I wonder how I made that mistake. thanks for the edit. approved. $\endgroup$ Nov 28, 2023 at 11:50
  • 1
    $\begingroup$ Thanks! Didn't see it at first aswell. More or less copied the example and noticed the comparisons always failed... :-) $\endgroup$
    – Ray
    Nov 28, 2023 at 11:53
1
$\begingroup$

There is no collection member in bpy.types.Object

instead you need to search the collection for the object:

def is_in_collection(name, obj):
    try:
        col = bpy.data.collections[name]
        for o in col.objects:
            if obj is o:
                return True
        return False
    except KeyError:
        return False
    return False
$\endgroup$
1
  • $\begingroup$ there is. it is in obj.users_collection which is a list of all the collections the object belongs to $\endgroup$ Jan 14, 2023 at 6:22

You must log in to answer this question.

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