Search Unity

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

Discussion in 'High Definition Render Pipeline' started by levere, Nov 8, 2019.

  1. levere

    levere

    Joined:
    Nov 8, 2019
    Posts:
    2
    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<MeshRenderer>();
    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):
    upload_2019-11-8_12-22-45.png

    After collapsing the "Surface Inputs" section in the inspector:
    upload_2019-11-8_12-47-33.png
     
  2. Bitshuffler

    Bitshuffler

    Joined:
    Oct 16, 2018
    Posts:
    7
    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");
    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. :/

    upload_2019-11-13_17-39-51.png
     
  3. Remy_Unity

    Remy_Unity

    Unity Technologies

    Joined:
    Oct 3, 2017
    Posts:
    704
    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 :)
     
    rbcode likes this.
  4. levere

    levere

    Joined:
    Nov 8, 2019
    Posts:
    2
    Thanks, guys. Those tips were incredibly helpful.