Copying materials between objects

I am attempting to copy the materials assigned to one object to another.
So far after trying a whole raft of ideas I am not having any luck. Does anyone have experience in this area?

The scene setup:

  • a mesh cube named ‘cube’
  • a mesh sphere named ‘sphere’
  • cube has a single material named ‘matcube’
  • sphere has a single (and different) material named 'matsphere’From running the code below, I would expect that the object ‘cube’ would have an additional material added to its collection.

The Code:


from Blender import *
 
print "______________________________________________"
 
cube = Object.Get("Cube")
sphere = Object.Get("Sphere")
 
print "sphere Materials: ", sphere.data.materials
print "cube Materials: ", cube.data.materials
 
print "attempting assign..."
cube.data.materials += [sphere.data.materials[0]]
 
print "sphere Materials: ", sphere.data.materials
print "cube Materials: ", cube.data.materials

The Output:


___________________________________________
sphere Materials:  [[Material "matsphere"]]
cube Materials:  [[Material "matcube"]]
attempting assign...
sphere Materials:  [[Material "matsphere"]]
cube Materials:  [[Material "matcube"]]

I expected that the last line of the output would be


cube Materials:  [[Material "matcube"], [Material "matsphere"]]

I found this thread/post which linked to http://wiki.blender.org/index.php/BSoD/Introduction_to_Python_Scripting/Materials
which in turn contained the answer to my problem - as I suspected the problem is to do with the way that I am getting objects, and the original example above must be returning NMesh rather than Mesh.

And that would explain my issue.

Essentially, the code needs to be changed to read:


import Blender
 
print "______________________________________________"
 
cube = Blender.Mesh.Get("Cube")
sphere = Blender.Mesh.Get("Sphere")
 
print "sphere Materials: ", sphere.materials
print "cube Materials: ", cube.materials
 
print "attempting assign..."
cube.materials += [sphere.materials[0]]
 
print "sphere Materials: ", sphere.materials
print "cube Materials: ", cube.materials

The resulting output is:


______________________________________________
sphere Materials:  [[Material "matsphere"]]
cube Materials:  [[Material "matcube"]]
attempting assign...
sphere Materials:  [[Material "matsphere"]]
cube Materials:  [[Material "matcube"], [Material "matsphere"]]

Which is exactly what I expected.