Drag this on the GameObject. You will need the Custom/VertexColorShader
which can also be found on here.
using UnityEngine;
public class ProceduralSphere : MonoBehaviour
{
public float radius = 1.0f;
public int subdivisions = 16;
public Color color = Color.white;
private void Start()
{
// Create a new mesh
Mesh mesh = new Mesh();
// Define the vertices of the sphere
Vector3[] vertices = new Vector3[(subdivisions + 1) * (subdivisions + 1)];
for (int i = 0; i <= subdivisions; i++)
{
float v = (float)i / (float)subdivisions * Mathf.PI;
float sinV = Mathf.Sin(v);
float cosV = Mathf.Cos(v);
for (int j = 0; j <= subdivisions; j++)
{
float u = (float)j / (float)subdivisions * Mathf.PI * 2.0f;
float sinU = Mathf.Sin(u);
float cosU = Mathf.Cos(u);
int index = i * (subdivisions + 1) + j;
vertices[index] = new Vector3(sinU * sinV, cosV, cosU * sinV) * radius;
}
}
// Define the triangles that make up the sphere
int[] triangles = new int[subdivisions * subdivisions * 6];
int triangleIndex = 0;
for (int i = 0; i < subdivisions; i++)
{
for (int j = 0; j < subdivisions; j++)
{
int index = i * (subdivisions + 1) + j;
triangles[triangleIndex++] = index;
triangles[triangleIndex++] = index + 1;
triangles[triangleIndex++] = index + subdivisions + 1;
triangles[triangleIndex++] = index + 1;
triangles[triangleIndex++] = index + subdivisions + 2;
triangles[triangleIndex++] = index + subdivisions + 1;
}
}
// Define the colors of each vertex
Color[] colors = new Color[vertices.Length];
for (int i = 0; i < colors.Length; i++)
{
colors[i] = color;
}
// Assign the vertices, triangles, and colors to the mesh
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.colors = colors;
// Create a new mesh renderer and assign the mesh to it
MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
meshRenderer.sharedMaterial = new Material(Shader.Find("Custom/VertexColorShader"));
// Create a new mesh filter and assign the mesh to it
MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();
meshFilter.mesh = mesh;
}
}