I need to take all the transforms applied to a GameObject and apply them to the actual mesh object it contains. I thought I could just use TransformPoint, but it doesn’t seem to do what it’s suppose to do. It returns the same vector as it’s given, not the transformed world coord vector. Am I misunderstanding TransformPoint’s purpose?
for (int i = 0; i < MainObject.sharedMesh.vertices.Length;i++)
MainObject.sharedMesh.vertices _= MainObject.transform.TransformPoint(MainObject.sharedMesh.vertices*);*_
How would I “bake” the transforms into the GameObject’s Mesh?
Edit:
(complete source code)
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
* void Awake () {*
//Create Test object with transforms
Mesh m = new Mesh();
m.vertices = new Vector3[] {new Vector3(1,1,1),new Vector3(2,2,2),new Vector3(3,1,1)};
m.uv = new Vector2[] { new Vector2(0, 0), new Vector2(1, 1), new Vector2(0, 1) };
m.triangles = new int[] {0,1,2};
m.RecalculateNormals();
GameObject go = new GameObject(“TEST OBJECT”);
MeshFilter mf = go.AddComponent();
mf.sharedMesh = m;
MeshRenderer mr = go.AddComponent();
mr.sharedMaterials = new Material[] { new Material(Shader.Find(“Diffuse”)) };
go.transform.Rotate(90, 0, 0);
go.transform.localScale = new Vector3(2, 2, 2);
//Create baked object from test object
GameObject goBaked = new GameObject(“Baked OBJECT”);
MeshFilter mfBaked = goBaked.AddComponent();
MeshRenderer mrBaked = goBaked.AddComponent();
Mesh mBaked = (Mesh)Instantiate(m);
mrBaked.sharedMaterials = mr.sharedMaterials;
mfBaked.sharedMesh = mBaked;
for (int i = 0; i < m.vertexCount; i++)
{
Debug.Log(“Before:” + m.vertices*);*
mBaked.vertices = go.transform.TransformPoint(m.vertices*);*
Debug.Log(“After:” + m.vertices*);*
}
* }*
}
MainObject.transform has local scale, local rotation, and local position that is applied, Debug printing before and after "TransformPoint" gives the exact same Vector3. I'm not sure why TransformPoint isn't working.
– anon99007248Yes. I've edited the original post to include a self-contained example source code. It creates the mesh item, sets it's transforms, then tries to retrieve the world coordinates of the vertices using "TransformPoint", with no luck.
– anon99007248It looks like it's the assignment that isn't working. Put this in your sample code inside of the loop: Debug.Log("Before:" + m.vertices*);* Vector3 transformedVert = go.transform.TransformPoint(m.vertices*);* Debug.Log("TransformedPoint:" + transformedVert); <em>mBaked.vertices = transformedVert;</em> <em><em>Debug.Log("After:" + mBaked.vertices*);*</em></em> <em><em>Take a look at the "TransformedPoint" debug log, that output looks correct at a glance.</em></em>
– anon32406522That helped quite a bit, I should have tried that before. Apparently vertices cannot be changed individually, I had to create a new vertices (Vector3) array, put all the new vert positions in it, then assign it back to the mesh all at once.
– anon99007248