unity 通过代码生成 球体mesh
时间: 2023-05-18 09:02:40 浏览: 73
可以使用Unity自带的Mesh类来生成球体的Mesh,以下是示例代码:
```csharp
using UnityEngine;
public class SphereGenerator : MonoBehaviour
{
public int numSegments = 32;
public float radius = 1f;
void Start()
{
MeshFilter meshFilter = GetComponent<MeshFilter>();
Mesh mesh = new Mesh();
meshFilter.mesh = mesh;
Vector3[] vertices = new Vector3[(numSegments + 1) * (numSegments + 1)];
Vector2[] uv = new Vector2[vertices.Length];
int[] triangles = new int[numSegments * numSegments * 6];
int index = 0;
for (int i = 0; i <= numSegments; i++)
{
float y = (float)i / numSegments;
for (int j = 0; j <= numSegments; j++)
{
float x = (float)j / numSegments;
float xPos = Mathf.Cos(x * 2f * Mathf.PI) * Mathf.Sin(y * Mathf.PI);
float yPos = Mathf.Cos(y * Mathf.PI);
float zPos = Mathf.Sin(x * 2f * Mathf.PI) * Mathf.Sin(y * Mathf.PI);
vertices[index] = new Vector3(xPos, yPos, zPos) * radius;
uv[index] = new Vector2(x, y);
if (i < numSegments && j < numSegments)
{
int topLeft = i * (numSegments + 1) + j;
int topRight = topLeft + 1;
int bottomLeft = (i + 1) * (numSegments + 1) + j;
int bottomRight = bottomLeft + 1;
triangles[index * 6] = topLeft;
triangles[index * 6 + 1] = bottomLeft;
triangles[index * 6 + 2] = topRight;
triangles[index * 6 + 3] = topRight;
triangles[index * 6 + 4] = bottomLeft;
triangles[index * 6 + 5] = bottomRight;
index++;
}
}
}
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}
```
这段代码会在场景中生成一个球体,并将其Mesh赋值给MeshFilter组件。你可以调整numSegments和radius来控制球体的细节和大小。