Coloured Cube

By Plump Helmet Studios on

Coloured Cube

Using a custom shader (assigned to a custom material), we are able to colour a cube with the vertex colour data provided to the mesh object.

VertexColour (Shader)

Shader "Custom/VertexColour"
{
  Properties
  {
    _Color ("Main Color", Color) = (1,1,1,1)
    _SpecColor ("Spec Color", Color) = (1,1,1,1)
    _Emission ("Emmisive Color", Color) = (0,0,0,0)
    _Shininess ("Shininess", Range (0.01, 1)) = 0.7
    _MainTex ("Base (RGB)", 2D) = "white" {}
  }

  SubShader
  {
    Pass
    {
      Material
      {
        Shininess [_Shininess]
        Specular [_SpecColor]
        Emission [_Emission]
      }

      ColorMaterial AmbientAndDiffuse
      Lighting On
      SeparateSpecular On

      SetTexture [_MainTex]
      {
        Combine texture * primary, texture * primary
      }

      SetTexture [_MainTex]
      {
        constantColor [_Color]
        Combine previous * constant DOUBLE, previous * constant
      }
    }
  }

  Fallback "VertexLit", 1
}

ColouredCube

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class ColouredCube : MonoBehaviour
{
    Mesh mesh;
    Vector3[] vertices;
    int[] triangles;
    Color32[] colors32;

    void Awake()
    {
        mesh = GetComponent<MeshFilter>().mesh;
        vertices = new Vector3[] {
            new Vector3(0, 0, 0), // front bottom left
            new Vector3(1, 0, 0), // front bottom right
            new Vector3(1, 1, 0), // front top right
            new Vector3(0, 1, 0), // front top left
            new Vector3(0, 1, 1), // back top left
            new Vector3(1, 1, 1), // back top right
            new Vector3(1, 0, 1), // back bottom right
            new Vector3(0, 0, 1)  // back bottom left
        };
        triangles = new int[] {
            0, 2, 1, // front
            0, 3, 2,
            0, 7, 4, // left
            0, 4, 3,
            5, 4, 7, // back
            5, 7, 6,
            1, 2, 5, // right
            1, 5, 6,
            2, 3, 4, // top
            2, 4, 5,
            0, 6, 7, // bottom
            0, 1, 6
        };

        colors32 = new Color32[] {
            new Color32(0, 255, 0, 255), // front bottom left
            new Color32(0, 240, 0, 255), // front bottom right
            new Color32(0, 225, 0, 255), // front top right
            new Color32(0, 210, 0, 255), // front top left
            new Color32(0, 195, 0, 255), // back top left
            new Color32(0, 180, 0, 255), // back top right
            new Color32(0, 165, 0, 255), // back bottom right
            new Color32(0, 150, 0, 255)  // back bottom left
        };
    }

    void Start()
    {
        mesh.Clear();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.colors32 = colors32;
        mesh.RecalculateNormals();
    }
}