Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Replace shader of material at build time

Discussion in 'Scripting' started by DevDunk, Jan 17, 2022.

  1. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,974
    I use a custom render pipeline to support specific Oculus tech (Application SpaceWarp) and my current shaders don't support it.

    If I build for android I want to change the shaders of all materials in my game to the URP simple lit shader. At runtime I just do .shader = simpleLitShader, but that gives graphical glitches because of spacewarp.

    Now I am trying to do it in the build process, using the code below, but the materials stick with the old custom shader and not simple lit.
    I also tried .material instead of sharedMaterial.

    Does anyone know if me or my code does something wrong?

    Code (CSharp):
    1. public class ShaderSwitch : IProcessSceneWithReport
    2. {
    3.     public int callbackOrder => 0;
    4.  
    5.     public void OnProcessScene(Scene scene, BuildReport report)
    6.     {
    7.         foreach(GameObject go in scene.GetRootGameObjects())
    8.         {
    9.             var renderer = go.GetComponent<Renderer>();
    10.             if (renderer)
    11.             {
    12.                 var tex = renderer.sharedMaterial.GetTexture("_Diffuse");
    13.                 if (tex)
    14.                 {
    15.                     Debug.Log("did it for " + renderer.material.shader.name);
    16.                     renderer.sharedMaterial.shader = Shader.Find("Universal Render Pipeline/Lit");
    17.                     renderer.sharedMaterial.mainTexture = tex;
    18.                 }
    19.             }
    20.         }
    21.     }
    22. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
  3. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,974
  4. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,974
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    FindObject(s)OfType<T>()
     
  6. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,974
    Ah of course, didn't think it was done that way