- Home /
Change vertex's world position
Hi, I'm trying to create bumps on my mesh. To do so, I have to tell every vertex of my mesh to change its "y" value. It worked fine, when I had one mesh. The problem started when I created chunks. So now I have few meshes and I need to get their world space coordinates. I read about it and used transform.TransformPoint(), but it doesn't work and I have no idea why. I spent hours on figuring out why it doesn't work and still I have no clue. This is what I got so far:
Vector3 test = transform.FindChild("2").GetComponent<MeshFilter>().mesh.vertices[1];
test += transform.TransformPoint(test);
test.y += 5;
transform.FindChild("2").GetComponent<MeshFilter>().mesh.vertices[1] = test;
print(transform.FindChild("2").GetComponent<MeshFilter>().mesh.vertices[1]);
Child called "2" is my second chunk. I have its vertices, but when I modify its "y" nothing happens.
Answer by Bunny83 · Oct 26, 2014 at 01:54 PM
There are several problems in your code:
the vertices array is a property. By using the index operator directly on it, the property will return a copy of the array which you index to get the actual vertex in local space. That's not a problem since reading would work that way. However you can't write it back that way since you, again, work on a copy of the array. To actually submit the changes you have to assign the whole changed array back to the property.
Your local "test" variable receives the vertex position in local space. You then use transform.TransformPoint to transform it into world space. But now you add the local space and the worldspace position together which makes absolutely no sense.
When you try assign the vertex back to the mesh you have to bring the position back into local space or the position will be a total mess.
Repeatedly using FindChild / GetComponent and reading the vertices property is a pure performance killer.
So do something like this:
// C#
Mesh mesh;
void Start()
{
mesh = transform.FindChild("2").GetComponent<MeshFilter>().mesh;
}
// wherever your code is
{
Vector3[] vertices = mesh.vertices;
Vector3 V = transform.TransformPoint(vertices[1]);
V.y += 5;
vertices[1] = transform.InverseTransformPoint(V);
mesh.vertices[1] = vertices;
Thank you very much! I totally forgot I have to change it back to local. It works great :)
Your answer
Follow this Question
Related Questions
UnityEngine.UI.Text characters mesh 0 Answers
Editing vertices 1 Answer
get terrain vertices? 2 Answers