Assigning a normal map to a runtime-created HDRP/Lit shader

I am looking to assign a normal map to a runtime-created material that uses the HDRP/Lit shader. The assignment seems to work and the values can be seen in the editor, but the normal map isn’t applied to the object. What’s particularly strange about this is that if I expand or collapse any of the material sections in the editor, the normal map is suddenly applied to the object correctly. Am I missing something here? Is there something I failed to update/flag?

public GameObject TestObject;
public Texture2D NormalTexture;

void Start()
{
var newMaterial = new Material(Shader.Find(“HDRP/Lit”));

AssignNormalTexture(newMaterial, NormalTexture);

var renderers = TestObject.GetComponentsInChildren();
foreach (var renderer in renderers)
{
renderer.sharedMaterial = newMaterial;
}
}

void AssignNormalTexture(Material material, Texture2D normalMap)
{
//tangent space
material.SetTexture(“_NormalMap”, normalMap);
material.SetFloat(“_NormalMapSpace”, 0.0f);
material.SetFloat(“_NormalScale”, 1.0f);
material.EnableKeyword(“_NORMALMAP”);
}

After assignment (normal map not applied to object):

After collapsing the “Surface Inputs” section in the inspector:

I’d have thought that setting that normalMapSpace value to zero (which it appears to be set to by default) should do it.

[Enum(TangentSpace, 0, ObjectSpace, 1)] _NormalMapSpace(“NormalMap space”, Float) = 0

However I’m gussing for some reasonit doesn’t pick up the shader variant. I needed to add the below.

material.EnableKeyword(“_NORMALMAP_TANGENT_SPACE”);
5169803--512969--upload_2019-11-13_17-36-20.png

Looks great in the editor, but when I create a build I get some weird shadow artifacts that move when I move the camera. Not sure if I’m missing a shader variant maybe?

Setting up assets in code is really not how unity prefers to be used. :confused:

Best for you would be to create the material in the editor with a “neutral” (8x8 px full 128, 128, 255) normal map so all the keywords and variants are properly set, and swap this texture at runtime :slight_smile:

1 Like

Thanks, guys. Those tips were incredibly helpful.