Using a Texture2D as a Normal Map

I’m trying to modify the normal map of a model on the fly in code. I have created a Texture2D and successfully assigned it to the normal map slot (“_BumpMap”) on the standard shader but the normal values don’t appear to be producing the correct effect. From other references, I thought the correct conversion was:

(r,g,b) = (0.5 + n.x/2, 0.5 + n.y / 2. 0.5 + n.z / 2)

but this looks wrong in the out. The result is too dark, similar to what happens if you using a texture as a normal map without importing it as one. This makes me think that maybe the texture importer does some filtering on the texture first?

The code I am using:

Texture2D normalMap = new Texture2D(width, height);
Color flat = new Color(0.5f, 0.5f, 1.0f);

var pixels = normalMap.GetPixels();
for (int i = 0; i < pixels.Length; i++) {
	pixels *= flat;*

}
normalMap.SetPixels(pixels);
normalMap.Apply();

MeshRenderer mr = GetComponent();
mr.material.SetTexture(“_BumpMap”, normalMap);

I found the answer here:

http://answers.unity3d.com/questions/170985/how-does-unity-handle-normal-maps-internally.html

Apparently Unity only stores the x and y components internally, since the z component can be computed from these (assuming it is normalised). They are stored in the alpha and green components respectively:

(r,g,b,a) = (0, 0.5 + v.y / 2, 0, 0.5 + v.x / 2)