前言
Unity中的text很容易遇到很多问题。
正文
字体模糊
当遇到字体很小时,就会遇到看不清的情况。
解决办法:
- 用TextMeshPro
- 如果有canvas,调节canvas的DynamicPixelsPerUnit值。
段落和标点
段落和标点符号其实挺烦人的,导致排版不太行,这个脚本可以让你消除这些烦恼。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
namespace SQFramework
{
public class TextExample : MonoBehaviour
{
public string strPath;
public Text t;
void Start()
{
strPath = Application.streamingAssetsPath + "/01.txt";
TextHelper.Instance().SetTextHandle(t,strPath);
}
}
public class TextHelper : MonoSingleton<TextHelper>
{
public string strPath;
private Coroutine coroutine;
void Start()
{
}
public void SetTextHandle(Text text, string path)
{
SetParagraph(text, File.ReadAllLines(path));
}
/// <summary>
/// 前提是我设置好了 每个段落是一行
/// </summary>
/// <param name="strContent"></param>
private void SetParagraph(Text text, string[] strContent)
{
//获得.txt文件的内容
string[] result = strContent;
string temp = string.Empty;
foreach (var item in result)
{
string str = "\u3000\u3000" + item + "\n";
temp += str;
}
Debug.Log(temp);
SetText(text, temp);
}
void SetText(Text _componet, string _text)
{
coroutine = StartCoroutine(RefillText(_componet, _text));
}
/// <summary>
/// 停止整理
/// </summary>
public void StopMex()
{
if (coroutine != null)
{
StopCoroutine(coroutine);
}
}
/// <summary>
/// 需要屏蔽的标点符号
/// </summary>
private readonly string symbolArr = @")}》】、‘“”’,。:;!?——.),.;:'!?]}-_=+/\";
/// <summary>
/// 整理文字,识别行首的标点符号,如果为标点符号,则把上一行的最后一个文字前添加空格,Text内的空格则识别为换行
/// </summary>
/// <param name="_component"></param>
/// <param name="_text"></param>
/// <returns></returns>
IEnumerator RefillText(Text _component, string _text)
{
_component.text = _text;
//需要一个延迟,否则_component.text来不及更新文字
yield return new WaitForSeconds(0.02f);
bool en = false;
int aa = 0;
while (!en)
{
string currentText = _component.text;
//获取当前的行
IList<UILineInfo> lines = _component.cachedTextGenerator.lines;
for (int i = 0; i < lines.Count - 1; i++)
{
int temp_0 = 0;
bool en_0 = false;
while (symbolArr.Contains(currentText[lines[i].startCharIdx - temp_0].ToString())/*向上寻找,如果上一行的末尾还是标点则继续寻找*/)
{
temp_0++;
en_0 = true;
}
if (en_0)
{
//如果当前行首为标点或者上一行末尾也有标点,则找到最后一个不是标点的字,在前面添加空格把它挤下来
currentText = currentText.Insert(lines[i].startCharIdx - temp_0, " ");
//插入了空格则后面的行都会变,所以需要重新获取行,重新遍历
break;
}
}
_component.text = currentText;
Debug.Log("一次");
yield return new WaitForSeconds(Time.deltaTime);
aa++;
//避免死循环,一遍循环即便就可以完全解决了
if (aa >= 50) break;
}
yield return null;
}
}
}
Comments | NOTHING