- Home /
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 ?
send your project folder to unity bug report or put it here as a link for others to test. i think it's a bug. if it isen't you might have some code on the object that do this.
Answer by Lucas Meijer 1 · Jan 21, 2010 at 11:06 PM
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)
Thank you. Actually, I access to renderer.materials[i].mainTextureOffset in the update function, which is composed of four lines in the form : renderer.materials[1].mainTextureOffset = Vector2 (0,0.offset). I just noticed that removing these lines prevents the materials from being destroyed without having to explicitly save them, so it seems that the problem comes from this access. I will bug it.
Answer by Bovine · Jan 15, 2011 at 01:12 AM
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.
Your answer
Follow this Question
Related Questions
Changing two different objects renderer colour 1 Answer
How to clean up after changing Renderer.material? 2 Answers
Destroy mesh / material after attaching to renderer 0 Answers
appear/disappear gameobject 3 Answers
Renderer.material not cloning? 3 Answers