因為剛入公司不久,一直在做UI,前兩天老大讓我改一下默認UI字體,我看了下UI目錄,十幾個子目錄,幾十個UI預制體,每個UI下的Text對象數量不確定,而且Text對象所在的層還不確定,找一個預制體下的所有Text對象再修改至少需要2分鍾時間。如果我手動一個個找並修改,這活不用2小時是干不完的。網游的UI你懂得,多而復雜。
所以我並沒有拼手速,而是開始了制作一個簡易插件,現在把這個插件分享一下,相當於給大家提供一個編輯器工具學習的例子吧。
首先需求很明確,就是選中一個預制體,並將他的子對象中的Text組件的字體修改為公司要求的字體。
首先,不能在運行條件下修改,因為公司的UI架構比較變態,各種組件有關聯。我開始懶省勁,運行加載所有的預制體,修改后保存,結果悲劇了,具體不想說。所以還是要通過編輯器代碼來修改。同時又不能更改預制體目錄,這就意味着不能使用Resources,以及其他限制。
好,介紹了那么多廢話,現在正題:
1,獲取到需要修改的預制體對象
2,獲取預制體下的所有Text對象,並篩選出需要修改的Text對象
3,修改Text對象的默認字體為要求字體。
我說一下第二步遇到的問題,獲取所有的Text組件。因為預制體中有些子對象是隱藏的,所以不能使用GetComponetsInChildren<>(),因為這個函數無法得到隱藏的對象,所以需要自己寫個找到所有子對象的函數。
接下來的就很簡單了,先弄個菜單編輯器,選中對象,並篩選,其代碼如下:
using UnityEngine; using System.Collections; using UnityEditor; using UnityEngine.UI; using System.Collections.Generic; public class TestFont { static GameObject targetObj; static string DefaultFont = "Arial";//默認字體的名稱 static List<Text> waiteForUpdate = new List<Text>(); static List<Transform> chindernList = new List<Transform>(); static Transform GetAllTransform(Transform parent) { foreach (Transform child in parent) { chindernList.Add(child); if (child.childCount > 0) GetAllTransform(child); } return null; } [MenuItem("FontEdit/SelectTarget")] static void ShowTextCount() { targetObj = Selection.activeGameObject;//這個函數可以得到你選中的對象 if (targetObj) { bool isok = false; chindernList.Clear(); GetAllTransform(targetObj.transform);//通過一個遞歸函數得到所有的子對象 for (int i = 0; i < chindernList.Count; i++) { Text _Text = null; if ((_Text = chindernList[i].GetComponent<Text>()) && (!_Text.font || _Text.font.name == DefaultFont)) { waiteForUpdate.Add(chindernList[i].GetComponent<Text>()); isok = true; } } if (isok) { if (!targetObj.GetComponent<FontSet>()) { targetObj.AddComponent<FontSet>(); } FontSet set = targetObj.GetComponent<FontSet>();//為對象添加個組件 set.UpdateFont(waiteForUpdate); chindernList.Clear(); waiteForUpdate.Clear(); GameObject.DestroyImmediate(targetObj.GetComponent<FontSet>());//修改完畢移除組件 } } } }
代碼很簡單,我就不詳細注釋了,接下來的代碼也很簡單,就是修改字體而已
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic; public class FontSet : MonoBehaviour { public Font UYFont; public void UpdateFont(List<Text> sets) { print(sets.Count); for (int i = 0; i < sets.Count; i++) { string str = sets[i].font == null ? "null" : sets[i].font.name; print(sets[i].name + ":" + str); sets[i].font = UYFont; } } }
需要注意的是,你要在選中這個腳本,然后在Inspector里面對字體對象賦值,這樣就可以放心的去修改了。
接下來就是一個個去選擇預制體,然后點擊FontEdit/SelectTarget就Ok了,剩下的玩家自己測試吧。很簡單的小插件,希望幫到你。
本文鏈接:http://www.cnblogs.com/jqg-aliang/p/4834488.html,轉載請申明出處,謝謝!