You can store materials' names, and then, when you need to use it - search for materials by name.
Of course this metod requires you to be strict about your file. You must not delete any materials by accident or change names.
Let's assume you have a list of materials:
materials = [bpy.data.materials["Marble"], bpy.data.materials["Glass"]]
# To get materials from object, use:
#bpy.context.object.material_slots[0].material
# or from the material list if you don't care about slots:
#bpy.context.object.data.materials[0]
Then you can write them into a Custom Property, separated with colons:
materialNames = []
for mat in materials:
materialNames.append(mat.name)
materialNames
are now ["Marble", "Glass"]
materialString = ",".join(materialNames)
materialString
is now "Marble,Glass"
.
You can save it to object's property:
bpy.context.object["materialString"] = materialString
And in other place, to get a real Blender material:
materialNames = bpy.context.object["materialString"].split( "," )
realMaterials = []
for matName in materialNames:
realMat = bpy.data.materials[matName]
realMaterials.append(realMat)
# check the results
# print(realMaterial[0].name)
First entry in realMaterials
list now again points to bpy.data.materials["Marble"]