三国卡牌客户端基础资源仓库
hch
2026-05-19 2b58e2ea2fc26e9aa58e960c2bbcde8f564ba0ae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
 
/// <summary>
/// 批量为所有 SpriteAtlas V2 文件添加 WebGL 平台设置(保留 Alpha 通道)。
/// 
/// 问题原因:项目所有 .spriteatlasv2 文件只配置了 Standalone/Android/iPhone 平台,
/// WebGL 没有平台覆盖,Unity 默认使用不含 Alpha 的压缩格式,导致运行时 Sprite 变为不透明。
/// 
/// 使用菜单:程序/Sprite/修复WebGL图集Alpha透明
/// </summary>
public class FixSpriteAtlasWebGLAlpha
{
    [MenuItem("程序/Sprite/修复WebGL图集Alpha透明")]
    public static void FixAllAtlases()
    {
        var guids = AssetDatabase.FindAssets("t:SpriteAtlas", new[] { "Assets/ResourcesOut" });
        int total = guids.Length;
        int fixed_count = 0;
 
        for (int i = 0; i < total; i++)
        {
            var assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
            EditorUtility.DisplayProgressBar("修复WebGL图集Alpha", $"处理: {assetPath}", (float)i / total);
 
            try
            {
                var importer = SpriteAtlasImporter.GetAtPath(assetPath) as SpriteAtlasImporter;
                if (importer == null)
                {
                    Debug.LogWarning($"[FixAtlasAlpha] 无法获取 SpriteAtlasImporter: {assetPath}");
                    continue;
                }
 
                var webGLSettings = importer.GetPlatformSettings("WebGL");
 
                // 已有 WebGL 覆盖且已是目标格式则跳过
                if (webGLSettings.overridden && webGLSettings.format == TextureImporterFormat.ASTC_8x8)
                {
                    continue;
                }
 
                // ASTC 8x8 — 含 Alpha 通道,与 Android/iPhone 保持一致
                webGLSettings.overridden = true;
                webGLSettings.maxTextureSize = 2048;
                webGLSettings.textureCompression = TextureImporterCompression.Compressed;
                webGLSettings.format = TextureImporterFormat.ASTC_8x8;
                webGLSettings.compressionQuality = 50;
                webGLSettings.allowsAlphaSplitting = false;
 
                importer.SetPlatformSettings(webGLSettings);
                importer.SaveAndReimport();
                fixed_count++;
 
                Debug.Log($"[FixAtlasAlpha] 已设置 WebGL=ASTC_8x8: {assetPath}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"[FixAtlasAlpha] 处理失败 {assetPath}: {ex.Message}");
            }
        }
 
        EditorUtility.ClearProgressBar();
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
 
        Debug.Log($"[FixAtlasAlpha] 完成!共修复 {fixed_count}/{total} 个图集。重新构建 AssetBundle 后生效。");
        EditorUtility.DisplayDialog("修复完成",
            $"共修复 {fixed_count}/{total} 个图集(WebGL 平台设置为 ASTC 8x8,含 Alpha)。\n\n请重新构建 WebGL AssetBundle 后测试。",
            "OK");
    }
}