- Home /
Problem importing normal map texture at runtime
I am having an issue importing a png image and using it as a normal map at runtime. This is my code:
t = new Texture2D(16, 16, TextureFormat.DXT5Crunched, false, true);
ImageConversion.LoadImage(t, _downloader.data, false);
Color[] colors = t.GetPixels();
Color c;
for (int q = 0; q < colors.Length; q++)
{
c = colors[q];
c.a = c.r;
c.r = 1; //have tried this with 0, same result
c.b = 0; // have tried this with 1, same result
colors[q] = c;
}
t.SetPixels(colors);
yield return null;
t.Compress(true);
t.Apply(false, true);
I have tried every single answer I could find online. This one comes from: https://forum.unity.com/threads/get-external-normal-map-at-runtime.532892/ and it's the answer given by the guy with the Unity Technologies tag. This solution gets me close but not close enough. Here is what the material is supposed to look like (with the texture imported into Unity and applied manually): And here is what it looks like with the normal map imported at runtime with this code: The difference is very noticeable if the camera moves around or gets far away. The main difference is that in the runtime material there is an overall tilt to the reflection.
The Texture2D is set to linear. I have tried it with mip maps (the result is worse) and without, compressed and un-compressed, and multiple formats. It's all the same result. Any ideas as to what I am missing here?
[EDIT]: Changed the example images to a different angle to better illustrate the problem.
Are you sure that your texture is actually a normal map and not just a bump map? Can you show your texture that you import at runtime?
I am 100% sure. Here is a scaled down version of the texture:
Sorry but your two provided screenshots in the question we can see barely a difference. Your normal map details are really $$anonymous$$imal. You may want to look at the result without the albedo texture (so render the cube with a solid color but with normal map). This might help to see if there's a difference.
As far as i know Unity uses the "DXT5nm" normal map format. So you probably should do:
c = colors[q];
c.a = c.r;
c.r = 0;
c.b = 0;
colors[q] = c;
Also note that the normalmap format might change depending on the platform / renderer used. This can be seen in the way the unpack normal shader helper is designed. Note the current implementation of UnpackNormal has already changed. Just look it up in your own Unity version in [...]\Editor\Data\CGIncludes\UnityCG.cginc
Your answer
Follow this Question
Related Questions
Run-time loaded Normal Map Lighting problem 1 Answer
Export Normal Map from Selected Mesh 0 Answers
Unity2D Tilemap Add Sprites with Normal Maps to tilePallet 2 Answers
Determine if a Texture2D has alpha 3 Answers
Changing Part Of Texture/Material 1 Answer