Drag this on the GameObject. You will need the Custom/VertexColorShader
which can also be found on here.
using UnityEngine;
public class ProceduralCube : MonoBehaviour
{
public float size = 1.0f;
public Color color = Color.white;
private void Start()
{
// Create a new mesh
Mesh mesh = new Mesh();
// Define the vertices of the cube
Vector3[] vertices = new Vector3[]
{
new Vector3(-size, -size, -size),
new Vector3(-size, -size, size),
new Vector3(-size, size, -size),
new Vector3(-size, size, size),
new Vector3(size, -size, -size),
new Vector3(size, -size, size),
new Vector3(size, size, -size),
new Vector3(size, size, size),
};
// Define the triangles that make up the cube
int[] triangles = new int[]
{
0, 1, 2, // front
2, 1, 3,
4, 0, 6, // back
6, 0, 2,
5, 4, 7, // right
7, 4, 6,
1, 5, 3, // left
3, 5, 7,
2, 3, 6, // top
6, 3, 7,
4, 5, 0, // bottom
0, 5, 1,
};
// Define the colors of each vertex
Color[] colors = new Color[]
{
color, color, color, color, color, color, color, 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;
}
}