您好,登錄后才能下訂單哦!
小編給大家分享一下使用unity獲取Text組件里text內容長度的案例,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
代碼如下:
/// <summary> /// 計算字符串在指定text控件中的長度 /// </summary> /// <param name="message"></param> /// <returns></returns> int CalculateLengthOfText(string message,Text tex) { int totalLength = 0; Font myFont = tex.font; //chatText is my Text component myFont.RequestCharactersInTexture(message, tex.fontSize, tex.fontStyle); CharacterInfo characterInfo = new CharacterInfo(); char[] arr = message.ToCharArray(); foreach (char c in arr) { myFont.GetCharacterInfo(c, out characterInfo, tex.fontSize); totalLength += characterInfo.advance; } return totalLength; }
補充:用Unity的TextAsset讀取TXT文檔內容,將物品信息存入字典中
Text Asset 文本資源
Text Assets are a format for imported text files. When you drop a text file into your Project Folder, it will be converted to a Text Asset. The supported text formats are:
文本資源是導入的文本文件的一個格式。當你拖入一個文本文件到你的項目時,他會被轉換為文本資源。支持的文本格式有:
.txt .html .htm .xml .bytes
Properties 屬性
Text
The full text of the asset as a single string.
之后需要新建一個文本txt來存放物品的屬性,這里以藥品為例
每一行文本對應一種物品,用逗號分隔,每個值對應屬性表里的每一列屬性。
之后新建c#腳本解析文本內容
private TextAsset objectsInfoListText; // 新建TextAsset變量 private Dictionary<int, ObjectInfo> objectInfoDict = new Dictionary<int,ObjectInfo>(); void Awake() { objectsInfoListText = Resources.Load("ObjectsInfoList") as TextAsset; // 從Resouces的path中讀取到文件 ReadInfo(); } void ReadInfo() { string text = objectsInfoListText.text; // 將文本內容作為字符串讀取 string[] objInfoArray = text.Split('\n'); // 以\n為分割符將文本分割為一個數(shù)組 foreach (string str in objInfoArray) // 遍歷每一行并將每一個藥品的值放入類對象中,并存入字典 { ObjectInfo info = new ObjectInfo(); string[] propertyArray = str.Split(','); int id = int.Parse(propertyArray[0]); string name = propertyArray[1]; string icon_name = propertyArray[2]; string str_type = propertyArray[3]; ObjectType type = ObjectType.Drug; switch (str_type) { case "Equip": type = ObjectType.Equip; break; case "Mat": type = ObjectType.Mat; break; case "Drug": type = ObjectType.Drug; break; } info.id = id; info.name = name; info.icon_name = icon_name; info.type = type; if (type == ObjectType.Drug) { int hp = int.Parse(propertyArray[4]); int mp = int.Parse(propertyArray[5]); int price_sell = int.Parse(propertyArray[6]); int price_buy = int.Parse(propertyArray[7]); info.hp = hp; info.mp = mp; info.price_sell = price_sell; info.price_buy = price_buy; } // 將物品信息存儲到字典中 objectInfoDict.Add(id, info); } } public enum ObjectType { Drug, Equip, Mat, }; public class ObjectInfo { public int id; public string name; public string icon_name; public ObjectType type; public int hp; public int mp; public int price_sell; public int price_buy; }
看完了這篇文章,相信你對“使用unity獲取Text組件里text內容長度的案例”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。