本文主要是介绍【Shader】Unity批量更换Shader,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Unity开发中,因为渲染管线问题,经常会遇到需要大量更改shader的问题,本篇文章讲述批量更换Shader的工具
一、原理:
- 拿到场景内、指定文件夹内所有模型或指定模型
- 编辑获取其Renderer上的所有材质球
- 记录原材质的颜色及贴图
- 更换新的shader
- 将颜色与贴图赋值给新的shader
二、代码
- 代码功能:(其他地方可自行更改)
- 更换场景内所有物体的shader
- 目标Shader为URP管线
public class BatchChangeShaderUtils : EditorWindow{private Shader targetShader;private int selectedShaderIndex = 0;private readonly string[] urpShaders = {"Universal Render Pipeline/Lit","Universal Render Pipeline/Simple Lit","Universal Render Pipeline/Unlit"};[MenuItem("MyTools/GameUtils")]public static void ShowWindow(){GetWindow<GameUtilsEditor>();}private void OnGUI(){GUILayout.Label("GameUtils", EditorStyles.boldLabel);selectedShaderIndex = EditorGUILayout.Popup("Target Shader", selectedShaderIndex, urpShaders);targetShader = Shader.Find(urpShaders[selectedShaderIndex]);if (GUILayout.Button("设置场景中所有对象的shader")) {if (targetShader != null){SetShaderForAllObjectsInScene(targetShader);}else{Debug.LogWarning("Please select a valid URP shader.");}}}private void SetShaderForAllObjectsInScene(Shader shader){GameObject[] allObjects = SceneManager.GetActiveScene().GetRootGameObjects();foreach (GameObject obj in allObjects){TraverseAndSetShader(obj, shader);}Debug.Log("Shader has been set for all objects in the scene.");}private void TraverseAndSetShader(GameObject obj, Shader shader){SetShaderForAllRenderers(obj, shader);foreach (Transform child in obj.transform){TraverseAndSetShader(child.gameObject, shader);}}private void SetShaderForAllRenderers(GameObject obj, Shader shader){Renderer[] renderers = obj.GetComponents<Renderer>();foreach (Renderer renderer in renderers){if (renderer != null){foreach (Material material in renderer.sharedMaterials){if (material != null){Color albedoColor = material.color;Texture albedoTexture = material.mainTexture;material.shader = shader;material.color = albedoColor;material.mainTexture = albedoTexture;}}}}}}
这篇关于【Shader】Unity批量更换Shader的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!