上一篇文章介绍了Unity的TMP和Text,TMP在渲染时需要先一张距离纹理,这不禁让我想到一种优化策略:如果对这张纹理选择不同图像压缩方式,是不是就可以以牺牲显示效果为代价,换取内存开销。

Unity SDF Asset结构

使用AlibabaPuHuiTi-3-65-Medium.ttf文件创建一个SDF Asset,选择渲染模式为static,并使用3500常用字生成贴图,可以看到Unity生成了一张4096*4096的纹理,并且大部分面积都存了字体。Unity还把纹理贴图当成了SDF Asset结构的一部分管理起来,不允许我们直接修改图像的压缩方式。
TMP_UseFont

TMP纹理的提取

不幸中的万幸,Unity把TMP的源码跟着package一起放在了本地,通过对于的编辑器界面逻辑,我找到了Unity保存纹理的过程代码。其中Save_Bitmap_FontAsset和Save_SDF_FontAsset都走向了执行的逻辑都相同,都是做了同样的三件事:
1、把纹理赋值给atlasTextures字段。
2、把纹理资源设置到FontAsset中。
3、更新FontAsset资源的材质主帖图为当前纹理。
TMP_Creator_Window
TMP_Save_Logic

我们的提取和替换逻辑:只需要从FontAsset下的atlasTexture读出对应的texture保存,然后把FontAssest下的指定为我们保存的texture,最后再把FontAsset的资源删除,就大功告成了。把相关思路灌给AI,然后AI生成了代码。下面给出核心的代码逻辑。

导出代码

在FontAsset中atlasTexture是public的所以直接读取,因为Unity默认没开纹理贴图的read/Write,所以MakeTextureReadable把图拷贝到一个新的texutre中,并保存下来。

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
private void ExportCurrentFontTexture()
{
if (targetFont == null || targetFont.atlasTexture == null)
{
EditorUtility.DisplayDialog("错误", "请先选择有纹理的TMP字体!", "确定");
return;
}

string savePath = EditorUtility.SaveFilePanel(
"导出字体纹理",
Application.dataPath,
$"{targetFont.name}_SDF_Texture",
"png"
);

if (!string.IsNullOrEmpty(savePath))
{
ExportTextureAsPNG(targetFont.atlasTexture, savePath);
}
}

private void ExportTextureAsPNG(Texture2D texture, string path)
{
if (texture == null) return;

Texture2D readableTexture = MakeTextureReadable(texture);

byte[] pngData = readableTexture.EncodeToPNG();
File.WriteAllBytes(path, pngData);

if (readableTexture != texture)
{
DestroyImmediate(readableTexture);
}

//Debug.Log($"纹理已导出: {path}");
AssetDatabase.Refresh();
ConfigureTextureForSDF(path);
EditorUtility.DisplayDialog("成功", $"纹理已导出到:\n{path}", "确定");
}

private Texture2D MakeTextureReadable(Texture2D texture)
{
if (texture == null || texture.isReadable) return texture;

RenderTexture rt = RenderTexture.GetTemporary(
texture.width,
texture.height,
0,
RenderTextureFormat.ARGB32,
RenderTextureReadWrite.Linear
);

Graphics.Blit(texture, rt);

RenderTexture previous = RenderTexture.active;
RenderTexture.active = rt;

Texture2D readableTexture = new Texture2D(
texture.width,
texture.height,
TextureFormat.RGBA32,
false
);

readableTexture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
readableTexture.Apply();

RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(rt);

return readableTexture;
}

替换代码

替换的核心代码,非常简单,先遍历把所有的删掉,然后把输入的贴图指定回去,最后保存。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (targetFont.atlasTextures != null && targetFont.atlasTextures.Length > 0)
{
for (int i = 0; i < targetFont.atlasTextures.Length; i++)
{
var texture = targetFont.atlasTextures[i];
if (texture == null)
{
continue;
}

AssetDatabase.RemoveObjectFromAsset(texture);
DestroyImmediate(texture);
}
}

targetFont.atlasTextures = new Texture2D[] { replacementTexture };
targetFont.material.mainTexture = replacementTexture;

// 保存字体资产
EditorUtility.SetDirty(targetFont);
AssetDatabase.SaveAssets();

纹理压缩验证

现在在Inspector面板下,此SDF Asset的纹理贴图成功指定到保存出来的纹理。
TMP_A8
对其进行纹理格式改变,字体也同步模糊和清晰,说明修改成功!
TMP_ASTC8x8

内存优化效果

TMP_diff
在Game视图下,ASTC6x6和Aplpha 8(原生类型),看着差别不大,但是内存一个是16MB,一个是7.1MB,相差将近一倍。
TMP_diffMem

编辑器全部代码

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using TMPro;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;

public class TMPSpriteExporterWindow : EditorWindow
{
private TMP_FontAsset targetFont;
private Texture2D replacementTexture;
private Texture2D replacementSDFTexture;

private Vector2 scrollPosition;
private Texture2D processedPreviewTexture;

[MenuItem("Tools/TMP/SDF字体纹理替换器")]
public static void ShowWindow()
{
var window = GetWindow<TMPSpriteExporterWindow>("TMP SDF字体纹理替换器", true, typeof(SceneView));
window.minSize = new Vector2(450, 800);
}

private void OnGUI()
{
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);

EditorGUILayout.LabelField("TMP SDF字体纹理替换器", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("此工具用于替换TMP SDF字体的Font Atlas纹理。注意:SDF字体需要特殊的距离场数据。", MessageType.Info);

EditorGUILayout.Space(10);

// 1. 选择SDF字体
EditorGUI.BeginChangeCheck();
targetFont = (TMP_FontAsset)EditorGUILayout.ObjectField("目标SDF字体", targetFont, typeof(TMP_FontAsset), false);
if (EditorGUI.EndChangeCheck())
{
UpdatePreview();
}

if (targetFont != null)
{
DisplayFontInfo();
}

EditorGUILayout.Space(20);

// 2. 选择替换纹理
EditorGUILayout.LabelField("替换纹理设置", EditorStyles.boldLabel);

EditorGUI.BeginChangeCheck();
replacementTexture =
(Texture2D)EditorGUILayout.ObjectField("源PNG纹理", replacementTexture, typeof(Texture2D), false);
if (EditorGUI.EndChangeCheck())
{
UpdatePreview();
}

if (replacementTexture != null)
{
EditorGUILayout.HelpBox(
$"纹理尺寸: {replacementTexture.width}x{replacementTexture.height} | 格式: {replacementTexture.format}",
MessageType.None);
}

EditorGUILayout.Space(10);

// 4. 功能按钮
EditorGUILayout.BeginHorizontal();

if (GUILayout.Button("替换字体纹理", GUILayout.Height(30)))
{
ReplaceSDFFontTexture();
}

EditorGUILayout.EndHorizontal();

EditorGUILayout.Space(10);

if (GUILayout.Button("导出当前字体纹理", GUILayout.Height(30)))
{
ExportCurrentFontTexture();
}

EditorGUILayout.Space(20);

// 5. 预览区域
DrawPreviewSection();

EditorGUILayout.EndScrollView();
}

private void DisplayFontInfo()
{
EditorGUILayout.BeginVertical(EditorStyles.helpBox);

if (targetFont.atlasTexture != null)
{
EditorGUILayout.LabelField($"当前纹理: {targetFont.atlasTexture.width}x{targetFont.atlasTexture.height}",
EditorStyles.miniLabel);
EditorGUILayout.LabelField($"字符数量: {targetFont.characterTable?.Count ?? 0}", EditorStyles.miniLabel);

if (targetFont.material != null)
{
Shader shader = targetFont.material.shader;
bool isSDF = shader != null && shader.name.Contains("SDF");
EditorGUILayout.LabelField($"着色器: {shader?.name} {(isSDF ? "(SDF)" : "(Bitmap)")}",
EditorStyles.miniLabel);
}
}
else
{
EditorGUILayout.HelpBox("警告:此字体没有纹理图集!", MessageType.Warning);
}

EditorGUILayout.EndVertical();
}

private void UpdatePreview()
{
if (processedPreviewTexture != null)
{
DestroyImmediate(processedPreviewTexture);
processedPreviewTexture = null;
}
}

private void ReplaceSDFFontTexture()
{
if (targetFont == null)
{
EditorUtility.DisplayDialog("错误", "请先选择目标SDF字体!", "确定");
return;
}

if (processedPreviewTexture == null && replacementTexture == null)
{
EditorUtility.DisplayDialog("错误", "请先生成SDF纹理或选择源纹理!", "确定");
return;
}

Texture2D textureToUse = processedPreviewTexture ?? replacementTexture;

if (!EditorUtility.DisplayDialog("确认替换",
$"确定要替换 '{targetFont.name}' 的Font Atlas纹理吗?\n\n" +
$"新纹理: {textureToUse.width}x{textureToUse.height}\n" +
$"此操作会修改字体资产,请确保已备份!",
"替换", "取消"))
{
return;
}

try
{
EditorUtility.DisplayProgressBar("替换字体纹理", "处理中...", 0.5f);

if (targetFont.atlasTextures != null && targetFont.atlasTextures.Length > 0)
{
for (int i = 0; i < targetFont.atlasTextures.Length; i++)
{
var texture = targetFont.atlasTextures[i];
if (texture == null)
{
continue;
}

AssetDatabase.RemoveObjectFromAsset(texture);
DestroyImmediate(texture);
}
}

targetFont.atlasTextures = new Texture2D[] { replacementTexture };
targetFont.material.mainTexture = replacementTexture;

// 保存字体资产
EditorUtility.SetDirty(targetFont);
AssetDatabase.SaveAssets();

// 刷新场景
RefreshAllTMPTextComponents(targetFont);

EditorUtility.ClearProgressBar();


EditorUtility.DisplayDialog("成功",
$"已成功替换SDF字体纹理!\n\n" +
$"已刷新所有相关文本组件。",
"确定");
}
catch (System.Exception e)
{
EditorUtility.ClearProgressBar();
Debug.LogError($"替换SDF字体纹理失败: {e.Message}\n{e.StackTrace}");
EditorUtility.DisplayDialog("错误", $"替换失败: {e.Message}", "确定");
}
}

private void ConfigureTextureForSDF(string texturePath)
{
// 检查路径是否在Assets目录下
if (!texturePath.StartsWith("Assets/"))
{
// 尝试转换为相对路径
string relativePath = GetRelativeAssetPath(texturePath);
if (string.IsNullOrEmpty(relativePath))
{
Debug.LogError($"路径不在Assets目录下: {texturePath}");
EditorUtility.DisplayDialog("错误", "文件必须保存在Assets目录下才能修改导入设置", "确定");
return;
}
texturePath = relativePath;
}


TextureImporter importer = AssetImporter.GetAtPath(texturePath) as TextureImporter;
if (importer == null)
{
EditorUtility.DisplayDialog("修改贴图信息", $"importer为空!","OK");
return;
}

// 对于SDF纹理,启用alpha通道处理
importer.textureType = TextureImporterType.Default; // 使用单通道类型
importer.alphaSource = TextureImporterAlphaSource.FromInput;
importer.alphaIsTransparency = true;

importer.isReadable = false;
importer.wrapMode = TextureWrapMode.Clamp;
importer.filterMode = FilterMode.Bilinear;
importer.mipmapEnabled = false;
importer.sRGBTexture = false; // 对于SDF,通常使用线性颜色空间

// 设置各平台格式
SetPlatformSettings(importer, "Standalone", TextureImporterFormat.Alpha8, 4096, false);
SetPlatformSettings(importer, "iPhone", TextureImporterFormat.ASTC_6x6, 4096, true);
SetPlatformSettings(importer, "Android", TextureImporterFormat.ASTC_6x6, 4096, true);

// 应用更改
importer.SaveAndReimport();
//EditorUtility.DisplayDialog("修改贴图信息", $"修改成功","OK");
}

// 将绝对路径转换为Assets相对路径
private string GetRelativeAssetPath(string fullPath)
{
string dataPath = Application.dataPath;
if (fullPath.StartsWith(dataPath))
{
return "Assets" + fullPath.Substring(dataPath.Length).Replace("\\", "/");
}
return null;
}

private void SetPlatformSettings(TextureImporter importer, string platform,
TextureImporterFormat format, int maxSize, bool compressed)
{
var settings = new TextureImporterPlatformSettings();
settings.name = platform;
settings.overridden = true;
settings.format = format;
settings.maxTextureSize = maxSize;
settings.textureCompression = compressed ?
TextureImporterCompression.Compressed :
TextureImporterCompression.Uncompressed;
settings.compressionQuality = 50;

importer.SetPlatformTextureSettings(settings);
}

private void RefreshAllTMPTextComponents(TMP_FontAsset fontAsset)
{
if (fontAsset == null) return;

int count = 0;

// 刷新场景中的文本
TMP_Text[] sceneTexts = GameObject.FindObjectsOfType<TMP_Text>(true);
foreach (TMP_Text text in sceneTexts)
{
if (text.font == fontAsset)
{
text.ForceMeshUpdate();
EditorUtility.SetDirty(text);
count++;
}
}

// 刷新预制件
string[] prefabGUIDs = AssetDatabase.FindAssets("t:Prefab");
foreach (string guid in prefabGUIDs)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);

if (prefab != null)
{
TMP_Text[] prefabTexts = prefab.GetComponentsInChildren<TMP_Text>(true);
bool changed = false;

foreach (TMP_Text text in prefabTexts)
{
if (text.font == fontAsset)
{
text.ForceMeshUpdate();
EditorUtility.SetDirty(text);
changed = true;
count++;
}
}

if (changed)
{
PrefabUtility.SavePrefabAsset(prefab);
}
}
}

Debug.Log($"已刷新 {count} 个文本组件");
}

private Texture2D MakeTextureReadable(Texture2D texture)
{
if (texture == null || texture.isReadable) return texture;

RenderTexture rt = RenderTexture.GetTemporary(
texture.width,
texture.height,
0,
RenderTextureFormat.ARGB32,
RenderTextureReadWrite.Linear
);

Graphics.Blit(texture, rt);

RenderTexture previous = RenderTexture.active;
RenderTexture.active = rt;

Texture2D readableTexture = new Texture2D(
texture.width,
texture.height,
TextureFormat.RGBA32,
false
);

readableTexture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
readableTexture.Apply();

RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(rt);

return readableTexture;
}

private void ExportCurrentFontTexture()
{
if (targetFont == null || targetFont.atlasTexture == null)
{
EditorUtility.DisplayDialog("错误", "请先选择有纹理的TMP字体!", "确定");
return;
}

string savePath = EditorUtility.SaveFilePanel(
"导出字体纹理",
Application.dataPath,
$"{targetFont.name}_SDF_Texture",
"png"
);

if (!string.IsNullOrEmpty(savePath))
{
ExportTextureAsPNG(targetFont.atlasTexture, savePath);
}
}

private void ExportTextureAsPNG(Texture2D texture, string path)
{
if (texture == null) return;

Texture2D readableTexture = MakeTextureReadable(texture);

byte[] pngData = readableTexture.EncodeToPNG();
File.WriteAllBytes(path, pngData);

if (readableTexture != texture)
{
DestroyImmediate(readableTexture);
}

//Debug.Log($"纹理已导出: {path}");
AssetDatabase.Refresh();
ConfigureTextureForSDF(path);
EditorUtility.DisplayDialog("成功", $"纹理已导出到:\n{path}", "确定");
}

private void DrawPreviewSection()
{
EditorGUILayout.Space(20);
EditorGUILayout.LabelField("预览", EditorStyles.boldLabel);

EditorGUILayout.BeginVertical(EditorStyles.helpBox);

if (targetFont != null && targetFont.atlasTexture != null)
{
EditorGUILayout.LabelField("当前字体纹理", EditorStyles.centeredGreyMiniLabel);
Rect origRect = GUILayoutUtility.GetAspectRect(1.5f);
EditorGUI.DrawTextureTransparent(origRect, targetFont.atlasTexture, ScaleMode.ScaleToFit);

EditorGUILayout.LabelField($"尺寸: {targetFont.atlasTexture.width}x{targetFont.atlasTexture.height}",
EditorStyles.miniLabel);
}

if (processedPreviewTexture != null)
{
EditorGUILayout.Space(10);
EditorGUILayout.LabelField("生成的SDF纹理", EditorStyles.centeredGreyMiniLabel);

Rect newRect = GUILayoutUtility.GetAspectRect(1.5f);
EditorGUI.DrawTextureTransparent(newRect, processedPreviewTexture, ScaleMode.ScaleToFit);

EditorGUILayout.LabelField($"尺寸: {processedPreviewTexture.width}x{processedPreviewTexture.height}",
EditorStyles.miniLabel);

// 显示SDF预览
DrawSDFPreview(processedPreviewTexture);
}
else if (replacementTexture != null)
{
EditorGUILayout.Space(10);
EditorGUILayout.LabelField("源纹理", EditorStyles.centeredGreyMiniLabel);

Rect srcRect = GUILayoutUtility.GetAspectRect(1.5f);
EditorGUI.DrawTextureTransparent(srcRect, replacementTexture, ScaleMode.ScaleToFit);
}

EditorGUILayout.EndVertical();

// 警告信息
if (targetFont != null && replacementTexture != null)
{
if (targetFont.atlasTexture != null &&
(targetFont.atlasTexture.width != replacementTexture.width ||
targetFont.atlasTexture.height != replacementTexture.height))
{
EditorGUILayout.HelpBox(
"⚠️ 警告:纹理尺寸不匹配!\n" +
"SDF字体的字符UV映射可能不正确,建议使用相同尺寸的纹理。",
MessageType.Warning
);
}
}
}

private void DrawSDFPreview(Texture2D sdfTexture)
{
EditorGUILayout.BeginHorizontal();

// 原始预览
EditorGUILayout.BeginVertical(GUILayout.Width(position.width / 2 - 20));
EditorGUILayout.LabelField("Alpha通道", EditorStyles.miniLabel);

Rect alphaRect = GUILayoutUtility.GetAspectRect(1f);
EditorGUI.DrawTextureAlpha(alphaRect, sdfTexture, ScaleMode.ScaleToFit);
EditorGUILayout.EndVertical();

// 着色预览
EditorGUILayout.BeginVertical(GUILayout.Width(position.width / 2 - 20));
EditorGUILayout.LabelField("距离场预览", EditorStyles.miniLabel);

Rect colorRect = GUILayoutUtility.GetAspectRect(1f);

// 创建临时材质用于预览SDF
Material previewMat = new Material(Shader.Find("Hidden/TMP_SDFPreview"));
if (previewMat != null)
{
EditorGUI.DrawPreviewTexture(colorRect, sdfTexture, previewMat);
DestroyImmediate(previewMat);
}
else
{
EditorGUI.DrawTextureTransparent(colorRect, sdfTexture, ScaleMode.ScaleToFit);
}

EditorGUILayout.EndVertical();

EditorGUILayout.EndHorizontal();
}

private void OnDestroy()
{
if (processedPreviewTexture != null)
{
DestroyImmediate(processedPreviewTexture);
}
}
}
#endif