- Home /
How can I assign one color to one vertex?
I have written a method that allows me to click on the object and print out the vertex number nearest to the mouse click. I now want to assign that vertex a color so that I can then do multiple clicks and establish where those vertices are.
I'm not sure how to go about assigning the color to the individual vertex. Having looked at many examples, the color is always being applied to a range of values, which means that you're mainly dealing with array types, but I can't seem to translate this over to just one individual vertex.
So far I have written the following primitive code, which I know doesn't work but I'm not sure how to go about it.
int a = mesh.vertices[mesh.triangles[3 * triangleIndex + 0]]; //vertex number
Color32 black = new Color32(0, 0, 0, 1); //type color32
//here is where I want to assign black to the vertex number held in 'a'
mesh.colors32 = black;
Do I need to create a shader to do this? I've never made a shader before so not sure if this is how I should go about it? Ultimately, I won't be using these colors, I just need to use them so that visually I can see which vertices I have selected as I need them going forward in my project.
The $$anonymous$$esh class has an array of type Color. each color element in this collection corresponds to the vertex at the same index in the vertices array. The color array is optional, however, so if no colors are assigned when the mesh is created then it's likely to be empty. So, to assign a color to a certain vertex, you would do something like
Color32[] colors = mesh.colors32;
colors[0] = new Color32(0,0,0,255);
mesh.colors32 = colors;
Of course, you also need a shader that supports vertex colors. I believe there is a version of the Standard Shader available that included vertex colors.
Pay attention that is your example :
int a = mesh.vertices[mesh.triangles[3 * triangleIndex + 0]]; //vertex number
mesh.vertices is a Vector3 array. This can't be an int.
A user on the forum posted a Standard Shader that uses vertex colors, so you don't have to do it by yourself : https://forum.unity.com/threads/standard-shader-with-vertex-colors.316529/
Also, ins$$anonymous$$d of fully modifying the mesh, you can use $$anonymous$$eshRenderer.additionalVertexStream to only change the vertex color values : https://docs.unity3d.com/ScriptReference/$$anonymous$$eshRenderer-additionalVertexStreams.html
Answer by bschla · Apr 05, 2018 at 11:55 AM
mesh.colors32 (and mesh.colors) is an array with same entries as mesh.vertices array, so mesh.color[32] would describe the color of mesh.vertices[32]
and yes, Unity' standard shader does not support vertex colors, but you can tweak the standard shader a bit, to see the vertex colors or use particle shader (just to see colors)
maybe this will help: https://docs.unity3d.com/ScriptReference/Mesh-colors.html