在Unity中使用网格连接Vector3 []

时间:2016-03-23 07:56:37

标签: c# unity3d mesh

在我的Unity3d项目中,我想创建一个连接四个球体的网格。

我创建了一个新的四边形并将我的四个范围中的transform.position数组分配给我的四边形GetComponent<MeshFilter>().mesh.vertecies

由于这不起作用,我如何读取或写入 Unity中顶点的全局位置



我的解决方案(有效)

GameObject quad;
Transform[] spheres;
//asign values and do other stuff

void UpdateMesh(){
    Vector3[] newVerts = new Vector3[spheres.Length];
    for(int i = 0; i < newVerts.Length; i++){
        newVerts[i] = spheres[i].position - quad.transform.position;
    }
    quad.GetComponent<MeshFilter>().mesh.vertecies = newVerts;
}

1 个答案:

答案 0 :(得分:1)

这可能取决于你如何分配顶点 这是一个可以试验的工作示例,只需将其作为脚本附加到四元组:

using UnityEngine;

// adding ExecuteInEditMode attribute so we can easily see the results from the editor
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
public class VertexChanger : MonoBehaviour {

    // assign these from the editor
    public Transform Sphere0;
    public Transform Sphere1;
    public Transform Sphere2;
    public Transform Sphere3;

    // doing changes in update so we see this immediately from the editor
    void Update () {
        if (Sphere0 == null || Sphere1 == null || Sphere2 == null || Sphere3 == null) {
            return;
        } 
        // create a new array of vertices and assign it
        Vector3[] newVertices = new[] {
            Sphere0.transform.position,
            Sphere1.transform.position,
            Sphere2.transform.position,
            Sphere3.transform.position
        };
        MeshFilter meshFilter = GetComponent<MeshFilter>();
        meshFilter.sharedMesh.vertices = newVertices;

        // these calls are not strictly necessary here...
        meshFilter.mesh.RecalculateBounds();
        meshFilter.mesh.RecalculateNormals();
    }
}

请注意,只有按照正确的顺序设置球体时,这才能正常工作,否则您可能还需要重新计算网格的三角形数组。