So I am trying to change the UVs of a mesh inside the editor and I can’t seem to be able to make it work. When I try to assign new UV coordinates to a Mesh variable, the UV coordinates in the variable does not change.
theRect.y += theRect.height / 2;
if (GUI.Button(theRect, "Offset")){
for (i = 0; i < 4; i++){
selectedUVs <em>= Vector2(selectedUVs_.x + 0.25, selectedUVs*.y + 0.25);*_</em>
* }*
}
//Update the UVs here
for (i = 0; i < 4; i++){
_ theMesh.uv[(faceNum * 4) - (4 - i)] = selectedUVs*;
}*_
hitInfo.transform.gameObject.GetComponent(MeshFilter).sharedMesh.uv = theMesh.uv;
The line with theMesh.uv[(faceNum * 4) - (4 - i)] = selectedUVs*;
should be assigning the values properly (to my knowledge anyways). Am I missing something here?*
This is because you’re setting uvs on the array returned by the .uv property of class Mesh. But this property is not actually a reference directly to the Mesh’s own uv array - it is instead a deep copy of all the data it contains. So you’re telling Unity to give you a deep copy of the uv array for each iteration of the for-loop here:
theMesh.uv[(faceNum * 4) - (4 - i)] = selectedUVs*;*
And then you set the value at an index in each deep copy, and then it gets thrown away again afterwards. So your changes never truly make it into the Mesh’s actual uv array.
For the changes to take effect, you need to copy out the uv array ONCE, make changes to the copied array, then ASSIGN IT BACK to the target mesh. Then it’ll work.
Here’s an example:
// Grab a reference to the target mesh
Mesh meshYouWantToChange = GetComponent().mesh;
// Copy out the contents of its uv array (the property returns a deep copy of the data)
Vector2[] itsUVs = meshYouWantToChange.uv;
// Make changes to that copy
itsUVs[0] = new Vector2(0.5f, 0.5f);
// Assign it back to the target mesh.
meshYouWantToChange.uv = itsUVs;