在 Unity 中选择时(在运行时)如何显示立方体上的顶点?

How to show vertices on a cube when selected in Unity (during runtime)?

我正在尝试编写一个脚本,使立方体在运行时 selected 时变为蓝色并在其上显示立方体的顶点。所以基本上当点击时,它会显示所有顶点,然后允许用户 select 立方体的不同顶点。

这是我目前所做的,基本上只是将立方体变成蓝色。如何将立方体的顶点显示为球体?我希望以后能够 select 这些顶点。

using UnityEngine;
using System.Collections;

public class Cube : MonoBehaviour {
    void OnMouseDown() {
        Renderer rend = GetComponent<Renderer>();
        rend.material.color = Color.blue;
        //insert method to display vertices
    }
}

由于立方体和球体都是基元:

你找到这样的顶点(假设 cubeGameObject):

Vector3[] vertices = cube.GetComponent<MeshFilter>().mesh.vertices;

然后创建你的球体(需要 using System.Linq):

GameObject[] spheres = vertices.Select(vert =>
{
    GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere)
    sphere.transform.position = vert;
    return sphere;
})
.ToArray();

更新:好的,我现在看到你的问题是顶点太多了,这就是我要做的,我个人会把阈值设为你的球体的半径,这样一旦球体开始重叠,它们就会变成一:

float threshold = 0.1f;

public void CreateSpheres()
{
    List<GameObject> spheres = new List<GameObject>();
    foreach (Vector3 vert in vertices)
    {
        if (spheres.Any(sph => (sph.transform.position - vert) < threshold)) continue;

        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere)
        sphere.transform.position = vert;
        spheres.Add(sphere);
    }
}

无法使 Select 函数如前一个示例所示那样工作。如其他答案中所述,使用 GetComponent<MeshFilter>.mesh.vertices; 找到坐标。

void OnMouseDown() {
    Renderer rend = GetComponent<Renderer>();
    rend.material.color = Color.blue;
    Vector3[] vertices = GetComponent<MeshFilter>().mesh.vertices;
    Vector3[] verts = removeDuplicates(vertices);
    drawSpheres(verts);
}

顶点数组包含 24 个元素,原因如下 here。因此,编写了 removeDuplicates 函数来去除重复的顶点。此函数如下所示:

Vector3[] removeDuplicates(Vector3[] dupArray) {

    Vector3[] newArray = new Vector3[8];  //change 8 to a variable dependent on shape
    bool isDup = false;
    int newArrayIndex = 0;
    for (int i = 0; i < dupArray.Length; i++) {
        for (int j = 0; j < newArray.Length; j++) {
            if (dupArray[i] == newArray[j]) {
                isDup = true;
            }
        }
        if (!isDup) {
            newArray[newArrayIndex] = dupArray[i];
            newArrayIndex++;
            isDup = false;
        }
    }
    return newArray;
}

最后,使用此处显示的 drawSpheres 函数使用新的顶点数组绘制了球体:

void drawSpheres(Vector3[] verts) {
    GameObject[] Spheres = new GameObject[verts.Length];
    for (int i = 0; i < verts.Length; i++) {
        Spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        Spheres[i].transform.position = verts[i];
        Spheres[i].transform.localScale -= new Vector3(0.8F, 0.8F, 0.8F);
    }
}