I am completly lost here … I need to change my mesh.uv2 values using the sharedMesh.uv2 values as references.
Something like “uv2 = shareduv2 +1”
If I understood correctly the doc, changing my mesh.uv2 shouldn’t change the sharedMesh.uv2.
In the following code, the sharedMesh.uv2 value keeps incrementing abnormally.
(its just a simple code with a cube to test the problem)
using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
void Update () {
Mesh mesh = GetComponent<MeshFilter>().mesh;
Vector2[] sharedUV =(Vector2[])GetComponent<MeshFilter>().sharedMesh.uv2;
Vector2[] uvs = new Vector2[sharedUV.Length];
Debug.Log (GetComponent<MeshFilter>().sharedMesh.uv2[2]);
uvs[2] = new Vector2(sharedUV[2].x+1,sharedUV[2].y+1);
mesh.uv2=uvs;
}
}
MeshFilter.mesh is an extremely badly designed API. Although it looks like a harmless property, the act of even reading from it - for the first time - causes sharedMesh to become a duplicate of mesh, losing its old value, and sometimes fairly innocuous code starts leaking meshes and memory really badly (check the memory profiler). If you let it carry on, it will eventually crash the editor (though not in your case as you don’t reassign to MeshFilter.mesh).
To achieve what you’re attempting, call MeshFilter.sharedMesh only once, on startup, before calling MeshFilter.mesh, and remember the result in a member variable. It will still overwrite sharedMesh when you do call MeshFilter.mesh for the first time, but that’s OK because you’ve got your own copy now.
I have come to the conclusion, though, that by far the safest way of dealing with procedural meshes - even modifications to existing meshes - is to ignore the ‘mesh’ member completely, and do everything through sharedMesh. For 100% procedural meshes that’s much easier. If the original mesh was an asset, though, you don’t want to modify it, but you can still manually clone it and assign that to sharedMesh, then pretend from then on that it was procedural in the first place.