Colors do not work with a mesh created in script?


I tried to generate mesh(just a triangle here) on the run from a script, and the colors don't work. The triangle appears always pink (looks like Color(255,0,255)). No matter what I set to the vertex colors to. Any idea why this could happen? Do I need to have a material/shader for this to work?

Here's the code

void Start() {

Mesh mesh = GetComponent<MeshFilter>().mesh;

mesh.vertices = new Vector3[] { new Vector3(-0.5f, 0, 0), 
                                new Vector3(0, 1, 0), 
                                new Vector3(0.5f, 0, 0) };

mesh.normals = new Vector3[] { new Vector3(0, 0,-1), 
                               new Vector3(0, 0,-1), 
                               new Vector3(0, 0,-1) };

mesh.colors = new Color[] { new Color(0,0,0), 
                            new Color(0,0,0), 
                            new Color(0,0,0) };

mesh.triangles = new int[] { 0, 1, 2 };


Yup, pink generally means missing shader.

You'll want to add a material with a vertex coloured shader on - there are a few of them on the wiki if you don't have one, e.g:


Here's the shader which you need to use with the mesh if you want to display only the interpolated vertex colors:

Shader "MyShader/VertexColor" {

    Category {
        BindChannels { 
            Bind "Color", color 
            Bind "Vertex", vertex
        SubShader { Pass { } }

I'm totally new to Unity and shaderLab language so I wasn't aware of this binding thing at all :)

EDIT: added vertex binding too (otherwise you get shader errors)

mesh.colors = new Color { new Color(0,0,0,0),
new Color(0,0,0,0),
new Color(0,0,0,0) };

I think you are missing last digit (alpha value) from color definition in your array.