三国卡牌客户端基础资源仓库
hch
2026-09-25 51497d37d2ea18aa4e439250119bb6f01224f519
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
74
75
76
77
78
79
80
81
82
83
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
 
/// <summary>
/// 新资源导入时自动设置平台压缩格式:
///   - 纹理(Texture2D):Android→ETC2(有Alpha→RGBA8 / 无Alpha→RGB4) iPhone→ASTC_6x6  WebGL→ASTC_6x6
///   - 图集(SpriteAtlas):Android→ETC2_RGBA8  iPhone→ASTC_6x6  WebGL→ASTC_6x6
///   - PC(Standalone):不设置覆盖,保持默认
/// 
/// 仅处理 Assets/ResourcesOut 下的资源。
/// </summary>
public class TexturePlatformAssetPostprocessor : AssetPostprocessor
{
    private static readonly string TARGET_FOLDER = TexturePlatformFormatHelper.TARGET_FOLDER;
    private static readonly bool AUTO_APPLY_ATLAS_SETTINGS = true;
 
    /// <summary>
    /// 防止回调中 SaveAndReimport 同步触发下一次 OnPostprocessAllAssets 造成嵌套重入。
    /// </summary>
    private static bool s_IsApplying;
 
    void OnPreprocessTexture()
    {
        if (!assetPath.StartsWith(TARGET_FOLDER))
            return;
 
        var importer = assetImporter as TextureImporter;
        if (importer == null)
            return;
 
        if (TexturePlatformFormatHelper.ApplyTexturePlatformSettings(importer))
        {
            Debug.Log($"[TexImport] 贴图: {assetPath}");
        }
    }
 
    static void OnPostprocessAllAssets(
        string[] importedAssets,
        string[] deletedAssets,
        string[] movedAssets,
        string[] movedFromAssetPaths)
    {
        if (!AUTO_APPLY_ATLAS_SETTINGS)
            return;
        // 回调里的 SaveAndReimport 会同步再次触发本回调,必须挡掉,否则会无限自触发
        if (s_IsApplying)
            return;
 
        s_IsApplying = true;
        try
        {
            foreach (var assetPath in importedAssets)
            {
                if (!assetPath.StartsWith(TARGET_FOLDER))
                    continue;
                if (!assetPath.EndsWith(".spriteatlasv2") && !assetPath.EndsWith(".spriteatlas"))
                    continue;
 
                try
                {
                    var importer = SpriteAtlasImporter.GetAtPath(assetPath) as SpriteAtlasImporter;
                    if (importer == null)
                        continue;
 
                    if (TexturePlatformFormatHelper.ApplyAtlasPlatformSettings(importer))
                    {
                        importer.SaveAndReimport();
                        Debug.Log($"[TexImport] 图集: {assetPath}");
                    }
                }
                catch (System.Exception ex)
                {
                    Debug.LogError($"[TexImport] 图集失败 {assetPath}: {ex.Message}");
                }
            }
        }
        finally
        {
            s_IsApplying = false;
        }
    }
}