![](https://img.haomeiwen.com/i1753433/7e2a4ad74d413e24.jpg)
早~
当项目到达一定的阶段,难免会遇到一些新需求,而如果有相应的工具,将会减少我们的工作量,今天给大家介绍 “游戏中一键更换Prefabs字体”,以此类推,可以实现很多类似的工具..... 自行脑补!
原理:
其实原理非常简单: 找到我们要替换的目标字体,然后遍历Resources下的所有Prefab,然后在获取单个Prefab中
所有的子组件(Label),修改其字体即可。
其中Unity为我们提供了一个AssetDatabase类,可以用来找到Asset下的同一类型游戏对象的id数组,然后根据
AssetDatabase.GUIDToAssetPath(id)这个方法可以获取到该对象的路径,最后LoadAssetAtPath即可。。。
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
class FontChangeEditor : EditorWindow
{
[MenuItem("Tools/一键切换字体XXX To YYY")]
static void OneKeyChangeFont()
{
Font mfont = NGUIEditorTools.LoadAsset<Font>("Assets/Resources/Fonts/YYY.TTF");
string[] guids = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Resources/UI/Prefab"});
if (guids!= null && guids.Length > 0)
{
EditorUtility.DisplayProgressBar("Replacing...", "Start replace", 0);
int progress = 0;
foreach (string guid in guids)
{
progress++;
string path = AssetDatabase.GUIDToAssetPath(guid);
EditorUtility.DisplayProgressBar("Replacing....", path, ((float)progress / guids.Length));
GameObject obj = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
bool isChanged = false;
UILabel[] lblist = obj.GetComponentsInChildren<UILabel>(true);
foreach (UILabel item in lblist)
{
if (item.TrueTypeFont.name == "XXX")
{
Debug.Log(item.TrueTypeFont.name + "===============" + obj.name);
item.TrueTypeFont = mfont;
}
}
if (isChanged)
{
EditorUtility.SetDirty(obj);
}
EditorUtility.ClearProgressBar();
AssetDatabase.SaveAssets();
}
}
}
}
注意:
预设体被修改后,一定要记得SetDirty(obj),这个函数是为了告诉Unity该对象所属于的Prefab已经发生了改变,
最后 AssetDatabase.SaveAssets()保存prefab。
代码非常简单,希望对大家有所帮助。
如有疑问,可以留言~ 一起学习。
网友评论