- Home /
The question is answered, right answer was accepted
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!
Answer by Radivarig · Jul 07, 2014 at 12:22 AM
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);
That didnt work for the mesh :/ It says $$anonymous$$esh doenst have a constructor with one argument.
You will have to duplicate each part of it and then store in a new $$anonymous$$esh(), look at this forum thread and try the scripts below, these guys were doing exactly what you need.
Alright well I used the script and it still changes the $$anonymous$$eshFilter.mesh to a 'Type$$anonymous$$ismatch' which then erases it. Also, the way suggested to duplicate materials did not work for me. It sill erases them :/ This is unnecessarily complicated.
Follow this Question
Related Questions
How can you duplicat folders and not share old dependencies? 1 Answer
What process should I best use to properly create an updated copy of a Prefab? 1 Answer
How should I structure this in Unity? 1 Answer
Duplicate a Material? (Project Window) 1 Answer
Prefab Materials and Meshes being deleted, How can I stop this 1 Answer