- Home /
How to pass vertex color information into GLSL shaders program
Hi, my question is how to pass per vertex color data into shader program in unity. Unlike in OpenGL c++ code, we define attributes and link it with shader program.
Example:
float vertices []
{
//vertex pos //vertex color
.0.0, 1.0, 0.0, 1.0, 0.0, 0.0,
1.0, 2.0, 1.0 0.0, 1.0, 0.0
}
and then we pass the data by parsing it based on size and offset size into vertex buffer. In unity "gl_vertex" take all vertex position data, but i want to pass color data too so that fragment shader can use it.
i want something like this,
//vertex shader
in vec4 color
out vec4 Color
void main()
{
gl_Position = gl_vertex //working fine
Color = color //expecting
}
//fragment shader
out vec4 fragcolor
in vec4 Color
void main()
{
outColor = Color
}
I found the information in here
https://en.wikibooks.org/wiki/Cg_Program$$anonymous$$g/Unity
I hope its still relevant!
Answer by Bunny83 · Dec 08, 2017 at 03:25 PM
Unity doesn't use specific vertex formats in their front-end interface to simplify the usage. The Mesh class has seperate arrays for the various vertex attributes:
If you want to define any of those attributes you just have to assign the appropriate array. Keep in mind that the all those arrays need to have the same length as the vertices array if you want to specify them. Do no initialize any Attributes you don't need.
Also note that the above mentioned properties of the Mesh class are properties and not fields. So you can't do this:
// this does NOT work
mesh.vertices = new Vector3[32];
mesh.vertices[0] = new Vector3(1, 2, 3);
mesh.vertices[1] = new Vector3(4, 5, 6);
// ...
When "reading" such a property Unity will actually create a new array. So those two "assignments" above (element 0 and 1) are pointless as the actual data isn't changed. To apply a change the property setter has to be invoked. So always use a temp variable or create the whole array at once
var vertices = new Vector3[3];
vertices[0] = new Vector3(1, 2, 3);
vertices[1] = new Vector3(4, 5, 6);
vertices[2] = new Vector3(7, 8, 8);
mesh.vertices = vertices;
var colors = new Color[vertices.Length];
colors[0] = new Color(1,0,0);
colors[1] = new Color(0,1,0);
colors[2] = new Color(0,0,1);
mesh.colors = colors;
// Or like this:
mesh.vertices = new Vertex3[]{
new Vector3(1, 2, 3),
new Vector3(4, 5, 6),
new Vector3(7, 8, 8)
};
mesh.colors = new Color[]{
new Color(1,0,0),
new Color(0,1,0),
new Color(0,0,1)
};
Also keep in mind to actually define triangles with the triangles array
Your answer
Follow this Question
Related Questions
Compile Shader Graph to GLSL 0 Answers
Shader fresnel effect working in URP but not working in HDRP 0 Answers
Shader to dilate a binary image 2 Answers