Unity3D中UGUI字体花屏问题

参考链接:http://www.xuanyusong.com/archives/4259

Unity版本2018.4.2f1,手机剧情聊天中出现了字体花屏问题。请教同事和在网上查阅资料,找到了原因:我们用的TTF动态字体,Text每次赋值的时候Unity会生成贴图,以及保存每个字的UV信息,显示字体的时候根据UV信息去生成的贴图里取对应的字,渲染在屏幕上。当显示新的文字剧情的时候,需要用到新的字,Unity重新生成字体贴图,之前的文字还在用老的UV坐标取字,就会出现字体花屏。理论上在生成新的文字贴图后重新刷新一下Text就能解决花屏问题。

解决方法:在展示文字的根节点添加以下组件,监听字体贴图变化,调用Text的刷新方法。

 1 using UnityEngine;
 2 using System.Collections;
 3 using UnityEngine.UI;
 4 
 5 public class UIFontDirty : MonoBehaviour
 6 {
 7     bool isDirty = false;
 8     Font dirtyFont = null;
 9 
10     private void OnEnable()
11     {
12         Font.textureRebuilt += FontChanged;
13     }
14 
15     private void OnDisable()
16     {
17         Font.textureRebuilt -= FontChanged;
18     }
19 
20     void LateUpdate()
21     {
22         if (isDirty)
23         {
24             isDirty = false;
25             var texts = transform.GetComponentsInChildren<Text>();
26             foreach (Text text in texts)
27             {
28                 if (text.font == dirtyFont)
29                 {
30                     text.FontTextureChanged();
31                 }
32             }
33             dirtyFont = null;
34         }
35     }
36 
37     void FontChanged(Font font)
38     {
39         isDirty = true;
40         dirtyFont = font;
41     }
42 }

猜你喜欢

转载自www.cnblogs.com/dingzhaoliang/p/12098169.html