Unity3D change standard shader rendering mode in runtime

https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html

"Instead, Unity tracks which variants you’ve used by examining the material assets used in your project. Whichever variants of the Standard Shader you have included in your project, those are the variants which are included in the build."


https://forum.unity3d.com/threads/access-rendering-mode-var-on-standard-shader-via-scripting.287002/

#29:

That looks to me like it should work, but it fails for me too and I don't know why. As a workaround I made a duplicate of the material I need and set it to fade mode in the editor, and then added an inactive GameObject to one of my scenes and made it use that fade-mode material. That seems to have forced the right shader to be included in the build and made switching the original material to fade mode at runtime work. Bit ugly, but it works.


新建一个标准材质,shader 选择standardshader的复制文件,该文件放在Resources文件夹里,rendering mode 选择standalone编译打包exe运行中需要的rendering mode ,scene中 添加gameobject,使用该材质。脚本中才可以变换rendering mode。

或者在project settings->graphics中默认添加默认shaderUnity3D change standard shader rendering mode in runtime

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

foreach (GameObject go in Gos) {
//Transform[] children = go.GetComponentsInChildren<Transform> ();
Renderer[] renderers = go.GetComponentsInChildren<Renderer> ();
foreach (Renderer render in renderers) { 
Material[] materials = render.materials;
foreach (Material material in materials) {
material.shader = Shader.Find ("FadeStandard");
if (slider.value > 0) {
material.SetOverrideTag ("RenderType", "Transparent");    //fade mode
material.SetInt ("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt ("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt ("_ZWrite", 0);
material.DisableKeyword ("_ALPHATEST_ON");
material.EnableKeyword ("_ALPHABLEND_ON");
material.DisableKeyword ("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
material.SetColor ("_Color", new Color (1, 1, 1, 1 - slider.value));
} else {
material.SetOverrideTag ("RenderType", "");//opaque mode
material.SetInt ("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt ("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt ("_ZWrite", 1);
material.DisableKeyword ("_ALPHATEST_ON");
material.DisableKeyword ("_ALPHABLEND_ON");
material.DisableKeyword ("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
}
}
}
}