Unity脚本一键修改所有预制体

需求

预制体中的Text组件默认是使用Unity的内置字体Arial。

但是在Unity2022之后,Text组件就被弃用了,内置字体Arial也移除了。

如果项目从2022之前的版本升到2022,那么Text组件的字体文件会自动改为LegacyRuntime.ttf文件。

其中LegacyRuntime.ttf文件是没有中文的。

所以我们需要将所有预制体的Text组件一键替换为我们存放在Assets目录下的字体

代码

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;

public class FontUpdater : EditorWindow
{
    private Font font;

    [MenuItem("工具/Update Font")]
    public static void ShowWindow()
    {
        GetWindow<FontUpdater>("Font Updater");
    }

    private void OnGUI()
    {
        GUILayout.Label("Update All Fonts");

        if (GUILayout.Button("Update Fonts"))
        {
            FindTextComponentsInAllPrefabs();
        }
    }
    
    private void FindTextComponentsInAllPrefabs()
    {
        font = AssetDatabase.LoadAssetAtPath<Font>("Assets/ArtFont/simsun.ttc");
        Debug.Log("FontName:" + font.name);
        // 查找所有预制体
        string[] prefabGUIDs = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" });
        List<string> prefabsWithText = new List<string>();

        foreach (string prefabGUID in prefabGUIDs)
        {
            string prefabPath = AssetDatabase.GUIDToAssetPath(prefabGUID);
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);

            if (prefab != null)
            {
                // 在预制体中查找 Text 组件
                Text[] texts = prefab.GetComponentsInChildren<Text>(true);
                if (texts.Length > 0)
                {
                    prefabsWithText.Add(prefabPath);
                    Debug.Log($"Prefab: {prefabPath} contains {texts.Length} Text components:");
                    foreach (Text text in texts)
                    {
                        Debug.Log($"  - {text.gameObject.name}");
                        text.font = font;
                    }
                    EditorUtility.SetDirty(prefab);
                }
            }
        }
        AssetDatabase.SaveAssets();
        if (prefabsWithText.Count == 0)
        {
            Debug.Log("No Text components found in any prefabs.");
        }
    }
}

其中要注意:

"Assets/ArtFont/msyh.ttc"这个路径是随意存放的。

EditorUtiliy.SetDirty(prefab)。

需要将prefab对象修改为脏对象,AssetDatabase.SaveAssets()才能成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值