Some of my object variables and components go “missing” even if I’ve called DontDestroyOnLoad on them. In the below project, my materials go missing.
I can tell it’s because I’m accessing their “color” value, making an instance I guess, but why doesn’t DontDestroyOnLoad still protect them? How do I keep them from disappearing?
Load the project and click “Load Another Level.” The cubes will lose their materials, except for one which has its script disabled.
The reason this happens is because DontDestroyOnLoad only protects the object it’s given, not any references to other objects that object may have.
Your problem is, as you’ve correctly ascertained, this line:
renderer.material.color = bright;
Which actually corresponds to the following:
var materialCopy = renderer.material;
materialCopy.color = bright;
Whenever you access the material property on a renderer it actually creates a new material, identical to the old one, assigns it to the renderer and then returns the reference to you.
One solution is to do a
DontDestroyOnLoad(renderer.material);
in your start function (apparently the DDOL status is carried over to new materials during the implicit copy, perhaps OTEE can elaborate on that (or correct me in case I’m completely of the mark ))
Whether this is expected behaviour, a feature or a bug, I’ll leave to OTEE.