- Home /
Modify Mesh and reset back to original at end of application
Im trying to modify the current mesh at run time and reset everything back to the way it was at the end of the application.
For some reason OnApplicationQuit runs as expected, once at the end of the application. But the mesh is not set back to the shared mesh. I know this because in the editor it stays the same, the copy i made is in the editor MeshFilter slot.
Ex: The MeshFilters mesh name is "Sphere", when this script runs it is replaced with "Sphere_temp", and when the application ends it should return back to "Sphere".
void Start ()
{
//get reference of sharedmesh
this.sharedMeshOriginal = GetComponent<MeshFilter>().sharedMesh;
//copy shared mesh
this.meshCurrent = new Mesh();
this.meshCurrent.name = this.sharedMeshOriginal.name + "_temp";
this.meshCurrent.vertices = this.sharedMeshOriginal.vertices;
this.meshCurrent.triangles = this.sharedMeshOriginal.triangles;
this.meshCurrent.uv = this.sharedMeshOriginal.uv;
this.meshCurrent.normals = this.sharedMeshOriginal.normals;
this.meshCurrent.colors = this.sharedMeshOriginal.colors;
this.meshCurrent.tangents = this.sharedMeshOriginal.tangents;
//set current mesh to new mesh
GetComponent<MeshFilter> ().mesh = this.meshCurrent;
}
void OnApplicationQuit ()
{
// set mesh back to original shared mesh
if (this.sharedMeshOriginal != null)
this.GetComponent<MeshFilter> ().mesh = this.sharedMeshOriginal; // NOT WORKING!!!!!
}
void Update()
{
//modify current mesh
}
Note: this.GetComponent ().mesh = this.sharedMeshOriginal; works fine if it runs in the update loop for somereason. The mesh is set back to the original with noproblem, but when it runs in OnApplicationQuit , it fails.
I don't see your problem, but you are going the long way around. Just use Instantiate() for making the copy of your mesh.
thanks for the installation() tip. But the problem still remains. When the application ends there is a "Sphere(Clone)" in the $$anonymous$$eshFilter.
Answer by Dreamora · Jun 22, 2014 at 10:23 PM
You are by error writing into .mesh instead of .sharedMesh. Writing into .mesh will always create a clone as you are trying to modify the mesh of just this instance which is not able to point to a 'global' mesh.
For the 'change during runtime', this is actually what you want to do, but in OnApplicationQuit you would want to use sharedMesh Unless something went wrong, Unity should have printed a warning to the Console too, informing you that the .mesh writing there is leaky, causing memory waste in your scene when done within the editor.
If you would want to alter just 1 mesh in the editor in a persistant way btw, you would want to instantiate the previous mesh and assign it to sharedMesh instead (or create a mesh and store it as a new asset through AssetDatabase)