Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity | mesh.colors won't color my custom mesh object

Tags:

unity3d

mesh

I have build a custom pyramid in Unity like this:

    Mesh mesh = GetComponent<MeshFilter>().mesh;
    mesh.Clear();
    Vector3[] vertices = {
        new Vector3(0.0f, 0.5f, 0.0f),
        new Vector3(0.5f, 0.0f, 0.5f),
        new Vector3(-0.5f, 0.0f, 0.5f),
        new Vector3(-0.5f, 0.0f, -0.5f),
        new Vector3(0.5f, 0.0f, -0.5f),
    };

    int[] triangles = {
        1, 2, 3,
        1, 3, 4,
        1, 0, 2,
        2, 0, 3,
        3, 0, 4,
        4, 0, 1
    };


    mesh.vertices = vertices;
    mesh.triangles = triangles;

I am trying to color my pyramid, as said in unity documentation like this:

    Color[] colors = new Color[vertices.Length];

    for (int i = 0; i < vertices.Length; i++)
        colors[i] = Color.Lerp(Color.red, Color.green, vertices[i].y);

    // assign the array of colors to the Mesh.
    mesh.colors = colors;

but this wont change a thing..

i have no materials on my object, only this script. Any ideas?

like image 532
Iraklis Bekiaris Avatar asked Apr 16 '19 17:04

Iraklis Bekiaris


2 Answers

Note that comment in mesh.colors

// (Note that most built-in Shaders don't display vertex colors. Use one that does, such as a Particle Shader, to see vertex colors)

so in order to see those colors in the MeshRenderer component add a material that uses such a Vertex or Particle Shader.

Therefore

  1. in the Project view (Assets) do right click &rightarrow; Create &rightarrow; Material

    enter image description here

  2. Give that material a name

  3. For the Shader from the Dropdown menu find and select e.g. Particles &rightarrow; Standard Unlit (or if you want to receive lightning Standard Surface)

    enter image description here

  4. Finally use this material for your object either by dragging it into the MeshRenderer &rightarrow; material or by simply dragging it onto the according object in the Scene view (the latter might not work if there is no mesh for that object yet)


Result:

enter image description here

like image 89
derHugo Avatar answered Nov 15 '22 11:11

derHugo


In addition to https://stackoverflow.com/a/55714190/617889:

When using Universal Render Pipeline you need to use other shaders:

  • Univeral Render Pipeline \ Particles \ Lit (with lightning)
  • Univeral Render Pipeline \ Particles \ Unlit (without lightning)
like image 23
oleh Avatar answered Nov 15 '22 12:11

oleh