1.在Unity场景中新建一个空物体,在空物体上添加MeshRenderer和MeshFilter组件。
2.新建一个C#脚本命名SphereMesh,将脚本挂载到空物体上,如图:
运行场景就可以看到生成一个球体
全部代码如下:
using UnityEngine;
public class SphereMesh : MonoBehaviour
{
void Start()
{
CreateSphereMesh();
}
void CreateSphereMesh()
{
MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>();
meshRenderer.sharedMaterial = new Material(Shader.Find("Standard"));
MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
Mesh mesh = new Mesh();
SphereShape shape = Init(20,20);
mesh.vertices = shape.vertices;
mesh.triangles = shape.index;
Vector3[] normal = new Vector3[shape.vertices.Length];
for (int i = 0; i < shape.vertices.Length; i++) {
normal[i] = -Vector3.forward;
}
mesh.normals = normal;
mesh.uv = shape.uv;
meshFilter.mesh = mesh;
}
SphereShape Init(int latCount, int lonCount)
{
if (latCount < 2 || lonCount < 2)
return null;
int totalIndexCount = 6 * (latCount - 1) * lonCount;
int totalVertexCount = (latCount + 1) * (lonCount + 1);
float latStep = Mathf.PI / latCount;
float lonStep = 2 * Mathf.PI / lonCount;
int[] index = new int[totalIndexCount];
Vector3[] vertices = new Vector3[totalVertexCount];
Vector2[] uv = new Vector2[totalVertexCount];
int currentVertex = 0;
int currentIndex = 0;
for (int lat = 0; lat <= latCount; lat++)
{
for (int lon = 0; lon <= lonCount; lon++)
{
vertices[currentVertex] = new Vector3(Mathf.Cos(lon * lonStep)*Mathf.Sin(lat * latStep),
Mathf.Sin(lon * lonStep) * Mathf.Sin(lat * latStep),
Mathf.Cos(lat * latStep - Mathf.PI)
);
uv[currentVertex] = new Vector2(
(float)lon / lonCount,
(float)lat / latCount
);
currentVertex++;
}
}
int v = lonCount + 1;
for (int lon = 0;lon < latCount; lon++)
{
index[currentIndex++] = lon;
index[currentIndex++] = v;
index[currentIndex++] = v + 1;
v++;
}
v = lonCount + 1;
for (int lat = 1; lat < latCount - 1; lat++)
{
for (int lon = 0; lon < lonCount; lon++)
{
index[currentIndex++] = v;
index[currentIndex++] = v + lonCount + 1;
index[currentIndex++] = v + 1;
index[currentIndex++] = v + 1;
index[currentIndex++] = v + lonCount + 1;
index[currentIndex++] = v + lonCount + 2;
v += 1;
}
v += 1;
}
for (int lon = 0; lon < lonCount; lon++)
{
index[currentIndex++] = v;
index[currentIndex++] = v + lonCount + 1;
index[currentIndex++] = v + 1;
v += 1;
}
SphereShape shape = new SphereShape();
shape.index = index;
shape.vertices = vertices;
shape.uv = uv;
return shape;
}
}
class SphereShape : Shape
{
}
class Shape
{
public int[] index;
public Vector3[] vertices;
public Vector2[] uv;
}
参考链接:
UV Sphere (winter.dev)https://winter.dev/projects/mesh/uvsphere