Search Unity

Switching materials based on URP Unlit and Lit shader during runtime

Discussion in 'Universal Render Pipeline' started by scuglik, Apr 6, 2021.

  1. scuglik

    scuglik

    Joined:
    Jan 17, 2013
    Posts:
    2
    Hello all,
    I have a problem with switching material during runtime. I have two mods of town. The first one is based on unlit shader with texture and the second one should be clear white material based on Lit or Simple Lit shader.

    The problem is when I switch material in builded project, some buildings will lose their lights and shadows. Seem like shader stayed unlit for some of them.

    upload_2021-4-6_11-56-8.png


    In editor everything works fine like this.
    upload_2021-4-6_11-54-9.png

    We tried everything to fix it but wihout any success. Build without static batching makes it worse. Lights and shadows aren't rendered at all.

    Material switcher script finds all components "OtherBuildings" in scene. It will cache old material and switch to new one like this

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class OtherBuilding : MonoBehaviour
    7. {  
    8.     MeshRenderer renderer;
    9.     Material[] cachedMaterials;
    10.  
    11.     void Start()
    12.     {
    13.         renderer = GetComponent<MeshRenderer>();
    14.         cachedMaterials = renderer.materials;
    15.     }
    16.  
    17.     public void SetClearMaterial(Material material)
    18.     {
    19.    
    20.             Material[] mats = new Material[renderer.sharedMaterials.Length];
    21.  
    22.             for (int i = 0; i < renderer.sharedMaterials.Length; i++)
    23.             {
    24.                 mats[i] = material;
    25.             }
    26.  
    27.             renderer.sharedMaterials = mats;
    28.  
    29.     }
    30.  
    31.     public void SetDefaultMaterial()
    32.     {
    33.         renderer.materials = cachedMaterials;
    34.     }
    35. }
    36.  
    37.  
    Do you have any idea how to solve it? I will be very grateful for any advice.
    Thank you very much for any response.
     

    Attached Files:

    Last edited: Apr 6, 2021