- Home /
How Does Unity Create Normal Maps from Grayscale?
The question is all in the title, whenever you import textures into Unity and set the texture type to normal map, you will be given the option to create a normal map from grayscale. Anybody have any idea on how this works and how to write virtually the same functionality to be executed at runtime?
Reading up on normal maps and Texture2D should be a good start. Basically, you're checking the value difference of the neighboring pixels in your grayscale texture and set the RGB (usually B stays unaffected) in your rendered normal map accordingly. If you think of it a bit more mathematically, if your grayscale map were a function and your pixels points on that function, you'd be looking for the normals at each point.
Depending on the hardware used and size of the texture that can take quite some time, though, especially when calculated on the CPU.
Answer by Chimera3D · Jun 09, 2014 at 01:25 AM
Found some code that works very well:
for (y=0; y < bumpTexture.height; y++) {
for (x=0; x < bumpTexture.width; x++) {
xLeft = bumpSource.GetPixel(x-1,y).grayscale;
xRight = bumpSource.GetPixel(x+1,y).grayscale;
yUp = bumpSource.GetPixel(x,y-1).grayscale;
yDown = bumpSource.GetPixel(x,y+1).grayscale;
xDelta = ((xLeft-xRight)+1)*0.5;
yDelta = ((yUp-yDown)+1)*0.5;
bumpTexture.SetPixel(x,y,new Color(xDelta,yDelta,1.0,1.0));
}
}
Source: http://forum.unity3d.com/threads/bumpmap-grayscale-to-normalmap-rgb.5714/
Your answer
![](https://koobas.hobune.stream/wayback/20220613151126im_/https://answers.unity.com/themes/thub/images/avi.jpg)