Files
ichni_Official/Assets/Shaders/ShaderExtension.cs
SoulliesOfficial 7580c4d87c 大更
2026-03-14 03:13:10 -04:00

53 lines
1.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class ShaderExtension
{
/// <summary>
/// 对于从AssetBundle中加载的材质修改Shader参数可能会出现异常情况。
/// 此时需要在生成物体的时候重新初始化Shader。
/// </summary>
public static void InitializeShader(this Renderer renderer)
{
// 关键改动:使用 sharedMaterials
Material[] sharedMats = renderer.sharedMaterials;
foreach (var material in sharedMats)
{
if (material == null) continue;
string shaderName = material.shader.name;
Shader shader = Shader.Find(shaderName);
if (shader != null)
{
// 只有当 Shader 真的不一致时才重新赋值,节省性能开销
if (material.shader != shader)
{
material.shader = shader;
}
}
else
{
Debug.LogWarning($"Shader '{shaderName}' not found for material '{material.name}' on renderer '{renderer.name}'.");
}
}
/*foreach (Material material in renderer.materials)
{
string shaderName = material.shader.name;
Shader shader = Shader.Find(shaderName);
if (shader != null)
{
material.shader = shader;
}
else
{
Debug.LogWarning($"Shader '{shaderName}' not found for material '{material.name}' on renderer '{renderer.name}'.");
}
}*/
}
}