Why does my materials get destroyed on some persistant objects ?

In my game, I have an object hierarchy whose root object calls the DontDestroyOnLoad function in its awake function. As a result, all the objects in this hierarchy are not destroyed when I load a new scene.

However, I have a mesh render object in this hierarchy which will lose all its materials when loading a new scene. The object is a sphere mesh with 5 materials and the object itself is not destroyed. The weird thing is that it has a child object which does not lose its material in the process.

I have solved the problem by adding the following code in its awake function :

function Awake() {
    for(m in renderer.materials)
    	DontDestroyOnLoad(m);
}

However, I do not understand why my materials are not automatically preserved from destruction. I have many other objects which do not lose their materials at loading, without having to save them explicitly.

Can someone shed some light on this ?

One thing that bites people sometimes is that if you do:

Material m = renderer.material;

we actually implicitely make a copy of the material, assign that to the renderer, and return that to you. (PS .sharedmaterial does not do this).

I could imagine this happening if you somehow access the .material property during initizliation of your object hierarchy. If that's not the case, please file a bug. (UnityMenu->Help->Report a problem)

You should try using sharedMaterials instead of materials. When you access materials you are creating copies. These copies are then discarded because they are not marked as don't destroy. Your fix makes them as such and hence it works.