move mesh verices in upate with unity 4.6.3, why so slowly??
GC happens automatically when the framework needs more memory. You are calling this method 2000 times per frame. And it’s producing 45 Mb of garbage.
Some context of what is happening in the scene, and what scripts you are using, would help.
Whenever you get the vertices from a mesh, Unity creates a new array. The moving is not the problem for you, it is the querying.
You should create the array once and re-use it, instead of constantly getting the vertices.
–Eric
hi all,thanks for reply~.Below is my codes ,I don.t know What unity does…confused!
Vector3 vertes[];
void Update()
{
vertes=mesh.vertices;
int i=0;
while(i<vertes.Length)
{
vertes[i]+=Vector3.forward*Time.deltaTime;
i++;
}
mesh.vertices=verts;
}
How to fixed this?
I already answered that…create the array once. You’re creating it every Update.
–Eric
I just move the vertics which already exist only once…no create new array…
you can try this:
void Update()
{
int i=0;
while(i<mesh.vertices.Length)
{
mesh.vertices[i]+=Vector3.forward*Time.deltaTime;
i++;
}
}
vertes=mesh.vertices;
This line is written in your update function. Just put it in the start function instead and make the transformation only in the update.
but how can move vertices in update,if not use “mesh.vertices+=Vector3.forward*Time.deltaTime;”
if use mesh.vertices then create gc collection,this is the point.
As mentioned, you need an array that you initialize e.g. in Start.
private Vector3[] vertices;
private void Start () {
vertices = mesh.vertices;
}
Your update will look as follows:
private void Update () {
int i = 0;
while (i < vertices.Length) {
vertices[i] += Vector3.forward * Time.deltaTime;
i++;
}
mesh.vertices = vertices;
}
For the future it would make sense if you could post the code earlier. This makes it a lot easier to help. One of the issues is this:
while(i<mesh.vertices.Length)
You just want the number of vertices, but what you get is the actual array each time and then it checks how many elements are in it. When you check the API, you will see that you can avoid that by using mesh.vertexCount. However, if you are using the solution as described earlier, this is not needed.
Normally this code wouldn’t cause real issues. A reference is pretty light weight, and you can often throw them away without bothering he GC to much.
But this is a special case.
Every time you call Mesh.verticies it copies into a new array. So the entire array gets GC’d every frame. This is expensive.
This behaviour is documented, and there are good performance reasons for it. But it is different from how arrays normally behave, so be wary.
OK,thanks all! Got it!