Unity material to vertex color.

I have a mesh with a material, the material is entirely pure colors, such as red, blue, etc. I want to be able to take the color that corresponds on the material and apply it as a vertex color, to each of the meshes vertices.

I know how to access all the vertices of the mesh and how to change their vertex color, my main problem is that i can not figure out how to find out where they are assigned to the material and what color is there.

Does anyone know anything about this or have any info about it?

If I understand what you’re asking for, you want to apply the color from a material, presumably either set with a texture or directly as the material’s color property, and copy that to the colors of that mesh’s vertices so you don’t need the texture / single color material?

You can search for Vertex Color Baking for examples of this out there on the internet. But here’s the short version:

To get the color of the material, you need the material in question, then you can get the color of the material with the material.GetColor() function. Note: You will need to know the real name of the material’s color property! This might be "_Color", or "_BaseColor", or almost literally anything if it’s a custom shader you’re trying to get the color value from, as the name is defined by the shader. And be aware the display name (what shows up in the inspector) and the actual property name are not necessarily even remotely similar. You’ll have to look at the shader source code to know for sure. But the two I listed above are the most common values for the BIRP and SRP shaders.

If you’re using a texture you need to get the color value from, that’s a bit more work. For that you’ll need the material, and the texture the material is using. To get the texture you’ll need the material.GetTexture() function, for which you’ll also need the real property name of the texture. Usually "_MainTex" or "_BaseMap"

You’ll also need to extract the UVs for each vertex of the mesh, which you can get via mesh.uv or the mesh.GetUVs() function.

And then you can get the color of the texture at that point using the texture2D.GetPixel() or texture2D.GetPixelBilinear() functions, passing in that vertex’s UV.

Finally you can set the current vertex color of a mesh using the mesh.colors or mesh.Get/SetColors() functions.

Some gotchas are the mesh you modify needs to be writable. By default any mesh that’s imported from an external file will not be. You can change the asset to allow for read/write, but you may also want to just save this data to a new mesh asset instead of overriding the old asset as if the original file changes or is removed the new asset will be updated or removed as well.

2 Likes