Swapping object's data from one collection to another randomly

I have two collections, source and target. I would like to replace all the object’s data in the target collection by the ones in the source collection, randomly. It’s easy to do it in the interface using CTRL-L → Object data but that will only do it from the last object selected. Anyone?

swap.blend (911.7 KB)

untested code off the top of my head:

import bpy
from random import randrange

source = bpy.data.collections['source'].objects
target = bpy.data.collections['target'].objects

for o in target:
    # note that this doesn't prevent repeats. if you're just looking to 'scramble' things and avoid
    # repeating data, you'll want to keep track of indices that have already been used and skip them on 
    # future passes. or just pop them out of the source list.
    o.data = source[randrange(0, len(source))].data
1 Like

Awesome! Thank you so much!

1 Like

Actually I should have tried it before flagging it as a solution :slight_smile:
I get this error message: NameError: name ‘random’ is not defined.

I added import random but then I get
name destination is not defined.

ah yeah, check updated code- that’s what i get for doing shit off the top of my head :wink:

Woohoo! Perfect! You have no idea how much trouble you saved me. I’m converting a series of scenes from Maya to Blender. Some were setup with Arnold, others with Renderman. They are bushes instances, four kinds. So I reversed engineered my scene. I replaced all the Renderman or Arnold bushes by cubes in Maya, properly named. Export the scene in alembic and in Blender I use your script to replace the cubes by the blender bushes. Works perfectly. Thanks again!