others - C# - 在Unity中,在mesh添加GameObject

我正在使用大约100个网格的FBX 3d模型,我想选择一个网格,并放置一个GameObject (多维数据集)在相同的位置,多维数据集已添加,但不在正确的位置-它不在viewport 中,我不知道如何确定网格的正确坐标。


Object prefab = Resources.Load("my_prefab"); // Assets/Resources/Prefabs/prefab1.FBX


var obj = (GameObject)Instantiate(prefab, new Vector3(370, 105, 100), Quaternion.identity);


obj.transform.localScale = new Vector3(150, 150, 150);



GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);


cube.name ="my_cube";


cube.GetComponent<Renderer>().material.SetColor("_Color", Color.red);


cube.transform.localScale = new Vector3(100, 100, 100);


cube.transform.parent = obj.transform;



var meshFilter = FindMesh(obj.GetComponentsInChildren<MeshFilter>(),"head");



List<Vector3> vector3List = new List<Vector3>();



for (int i = 0; i < meshFilter.mesh.vertices.Length; ++i)


{


 vector3List.Add(obj.transform.TransformPoint(meshFilter.mesh.vertices[i]));


}



cube.transform.localPosition = vector3List[0];


Camera.main.transform.LookAt(obj.transform);



public MeshFilter FindMesh(MeshFilter[] mesh, string name)


{


 foreach (MeshFilter meshFilter in mesh)


 {


 if (meshFilter.name == name)


 {


 return meshFilter;


 }


 }


 return null;


}



我的代码有什么问题?


Object prefab = Resources.Load("ironman"); // Assets/Resources/Prefabs/prefab1.FBX


var obj = (GameObject)Instantiate(prefab, new Vector3(370, 105, 100), Quaternion.identity);


obj.transform.localScale = new Vector3(150, 150, 150);



GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);


cube.name ="my_cube";


cube.GetComponent<Renderer>().material.SetColor("_Color", Color.red);


cube.transform.localScale = new Vector3(10, 10, 10);



var components = obj.GetComponentsInChildren<Component>();


foreach (Component c in components)


{


 if (c.name =="head")


 {


 cube.transform.parent = c.transform;


 break;


 }


}



cube.GetComponent<Collider>().isTrigger = true;


Camera.main.transform.LookAt(cube.transform);



这是我使用的fbx : https://free3d.com/de/3d-model/iron-man-2-11174.html

我是Unity新手,我不知道如何将相机聚焦到游戏对象的子组件。

时间:


List<Vector3> vector3List = new List<Vector3>();



for (int i = 0; i < meshFilter.mesh.vertices.Length; ++i)


{


 vector3List.Add(obj.transform.TransformPoint(meshFilter.mesh.vertices[i]));


}



cube.transform.localPosition = vector3List[0];



可以简化为


cube.transform.localPosition = obj.transform.TransformPoint(meshFilter.mesh.vertices[0]);



cube.GetComponent<Collider>().isTrigger = true;防止cube响应碰撞并最终将localPosition更改为position

...