'Blender scripting all_objects not looping through all objects

while working on a script I stumbled across this funny issue, if someone can help me understand this bizarre behaviour, I would be very please.

Context

I have one collection with 4 assets I want to loop through all the assets and render each one of them in a separate file

My script looks like this

for obj in bpy.data.objects:
        if bpy.data.objects[obj.name].type == "MESH":
            bpy.data.objects[obj.name].hide_render = True
count = 0
collection1 = bpy.data.collections["Category1"]
for obj1 in collection1.all_objects:     
        obj1.hide_render = False
        Render_Scene(str(count))
        obj1.hide_render = True
        count += 1

and the output (wrong) is:

0.png
1.png

what's funny is that if I change the body of the loop with this:

for obj1 in collection1.all_objects:
        print(obj1.name)

the output is correct:

Cube
Icosphere
Cone
Cylinder

any suggestions? Thank you all



Solution 1:[1]

I have exactly the same problem (blender octane 2.93.2) To me it looks like a Blender bug. The code that doesn't work (there are 20 objects in the collection, that code affect only 2 or 3 objects):

for obj in get_all_from_collection(name):          
    sel_by_name(name)
    obj.hide_render = (random.choice([True, False]))

however this will print all objects in the collection:

for obj in get_all_from_collection(name):
    print("hiding/showing object " + obj.name)

The workaround that worked for me was to iterate over object names, not the collection. I renamed all objects to "Puzzle-xxx" and run that code successfully:

for index in range(1,20):
    name = "Puzzle-" + str(index)     
    print("hiding/showing object " + name)
    # move to 'tmp' collection
    if random.choice([True, False]) == True:        
        bpy.ops.object.move_to_collection(collection_index=6)

(I changed my strategy and I'm moving to a hidden collection instead of disabling render but that doesn't matter) It's a dirty workaround but it worked for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikeTS