Getting vertices of moved and scaled prefab
I want to get array of vertices of instantiated object and then use it as a feed to raycast over vertices of other mesh. Problem is with getting vertices of that instantiated object. Shortened version of my code:
prefab_PRE = Resources.Load ("prefabs/street") as GameObject;
current_position = new Vector3 (2 + highlight.posx, highest_mesh_y + 1f, 2 + highlight.posy);
prefab = GameObject.Instantiate (prefab_PRE,current_position, rotate_q, current_grass.transform) as GameObject;
mesh = prefab.GetComponent<MeshFilter> ().sharedMesh;
mesh = (Mesh)Instantiate (mesh);
prefab.transform.localScale = new Vector3 (0.2f, 0.2f, 0.2f);
for (int i = 0; i < mesh.vertices.Length; i++) { //For testing
Debug.DrawRay (mesh.vertices [i], Vector3.down, Color.green, 10);
}
Apparently, array mesh.vertices is referring to prefab_PRE's vertices, insted of prefab's (as I wanted it to be). I tried making mesh unique with
mesh = (Mesh)Instantiate (mesh);
but it hasn't worked as I expected. So how can I get to array of prefab's vertices?
Rays represent vertices of my "untransformed" asset 'street.3ds' (prefab_PRE), while prefab is that hovering road :>. Rays should cover only the road and nothing more.
Answer by neoking_unity · Jul 18, 2018 at 03:24 PM
Finally I got it. Mesh Filters property .vertices relates to local alignment of vertices of original object. Command:
prefab.GetComponent<MeshFilter>().sharedMesh.vertices
refers to vertices of original prefab. Moreover:
prefab.GetComponent<MeshFilter>().Mesh.vertices
means exactly the same. However, if you want to get unique mesh of prefab and operate on it, u need to get its .mesh, not .sharedMesh. If clone has been scaled, every change of vertex must by "back-scaled" so to speak. For example, if copy has been scaled down 5 times, then desired change of position of vertex has to be upscaled 5 times as well. Its strange, but it works. At least for me.