Possible Unity Glitch. A few lines of code erasing prefab data.

I was assuming that meshes and materials acted like everything else and using the ‘=’ operator would duplicate it:

 this.GetComponent<MeshFilter>().mesh = constructionPhases[0].GetComponent<MeshFilter>().mesh;
 this.renderer.materials = constructionPhases[0].renderer.materials;

And it erased my mesh and materials on my prefab! So, I remade the prefabs and changed the code to:

this.GetComponent<MeshFilter>().mesh = (Mesh) Instantiate(constructionPhases[0].GetComponent<MeshFilter>().mesh);
			
List<Material> ms = new List<Material>();
foreach(Material m in constructionPhases[0].GetComponent<MeshRenderer>().materials)
		ms.Add((Material) Instantiate(m));
this.GetComponent<MeshRenderer>().materials = ms.ToArray();

And again it erased the prefab component data! I can not keep remaking the prefabs. I need to know how to correctly duplicate a mesh and its materials.
Thank you in advance!

In your case ‘=’ operator passes a reference instead of duplicating it. When reference is passed you have to use constructor of the class you want to duplicate.

Try this

copiedMaterial = new Material(oldMaterialHolder.material);