Unity 资源导入设置脚本 笔记

0 阅读9分钟

核心说明:Unity 资源导入设置脚本,核心依赖 UnityEditor.AssetImporter 及其子类,用于批量修改、自动化配置资源的导入参数(替代手动在Inspector面板修改),适用于大量资源批量处理、项目规范统一、减少重复操作,仅在Editor模式生效(发布后无效)。

一、核心基础(必记)

1. 核心命名空间

所有导入设置脚本,必须引用以下命名空间(缺一不可):

using UnityEditor; // 核心命名空间,包含所有Editor相关API
using UnityEngine; // 基础命名空间,用于资源对象操作

2. 核心父类:AssetImporter

所有具体资源的导入器(如纹理、模型、音频),都继承自 AssetImporter,是脚本操作的核心入口。

核心方法(常用):

  • AssetImporter.GetAtPath(string path):根据资源在Project窗口的路径(相对路径,如 "Assets/Textures/xxx.png"),获取该资源的导入器对象。

  • assetImporter.SaveAndReimport():保存修改后的导入设置,并重新导入资源(必须调用,否则修改不生效)。

  • assetImporter.SetAssetBundleNameAndVariant(string name, string variant):设置资源的AssetBundle名称和变体(可选,用于资源打包)。

注意:路径必须以 "Assets/" 开头,且区分大小写,否则获取不到导入器。

3. 脚本生效场景

  • 脚本必须放在 Project 窗口的 Editor 文件夹下(或子文件夹),否则Editor API无法生效。

  • 仅在Unity编辑器中运行,发布后的游戏中,该类脚本会被自动剔除,不会占用包体。

  • 可通过「菜单栏按钮」「右键菜单」「自动触发(如资源导入时)」三种方式执行。

二、具体资源导入设置脚本(分类型,重点)

不同类型资源(纹理、模型、音频等),对应不同的导入器子类,需针对性操作,以下是常用类型的完整示例。

1. 纹理(Texture)导入设置脚本

对应导入器:TextureImporter(继承自AssetImporter),核心控制纹理的压缩、格式、尺寸、渲染模式等。

常用场景:批量设置UI纹理、场景纹理、图集纹理的统一规范。

using UnityEditor;
using UnityEngine;

/// <summary>
/// 纹理导入设置工具(笔记:批量处理纹理,统一规范)
/// </summary>
public class TextureImportSettingTool : EditorWindow
{
    // 窗口打开方式:菜单栏 -> 工具 -> 纹理导入设置
    [MenuItem("工具/纹理导入设置")]
    public static void OpenWindow()
    {
        GetWindow<TextureImportSettingTool>("纹理导入设置");
    }

    // 纹理导入参数(可在窗口中调整)
    private TextureImporterFormat textureFormat = TextureImporterFormat.Automatic; // 压缩格式
    private bool isReadable = false; // 是否可读写
    private int maxSize = 1024; // 最大尺寸
    private TextureImporterType textureType = TextureImporterType.Sprite; // 纹理类型(Sprite/Texture)

    private void OnGUI()
    {
        // 绘制参数面板
        textureType = (TextureImporterType)EditorGUILayout.EnumPopup("纹理类型", textureType);
        textureFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("压缩格式", textureFormat);
        isReadable = EditorGUILayout.Toggle("是否可读写", isReadable);
        maxSize = EditorGUILayout.IntField("最大尺寸", maxSize);

        // 批量应用按钮
        if (GUILayout.Button("批量应用选中纹理"))
        {
            ApplyTextureSettingsToSelected();
        }
    }

    /// <summary>
    /// 给选中的纹理应用导入设置
    /// </summary>
    private void ApplyTextureSettingsToSelected()
    {
        // 获取Project窗口中选中的资源
        Object[] selectedObjects = Selection.objects;
        if (selectedObjects == null || selectedObjects.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请在Project窗口中选中纹理资源!", "确定");
            return;
        }

        int successCount = 0;
        // 遍历选中的资源
        foreach (Object obj in selectedObjects)
        {
            // 获取资源路径
            string assetPath = AssetDatabase.GetAssetPath(obj);
            // 判断是否是纹理资源
            if (AssetDatabase.GetAssetTagString(obj) == "Texture2D")
            {
                // 获取纹理导入器
                TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                if (textureImporter != null)
                {
                    // 开始修改导入设置(笔记:以下是核心设置,可按需添加)
                    textureImporter.textureType = textureType; // 设置纹理类型
                    textureImporter.textureFormat = textureFormat; // 设置压缩格式
                    textureImporter.isReadable = isReadable; // 设置可读写
                    textureImporter.maxTextureSize = maxSize; // 设置最大尺寸
                    textureImporter.mipmapEnabled = false; // 关闭mipmap(按需开启)
                    textureImporter.wrapMode = TextureWrapMode.Clamp; // 纹理包裹模式(UI纹理常用Clamp)
                    textureImporter.filterMode = FilterMode.Bilinear; // 过滤模式

                    // 保存设置并重新导入
                    textureImporter.SaveAndReimport();
                    successCount++;
                }
            }
        }

        EditorUtility.DisplayDialog("完成", $"共处理 {selectedObjects.Length} 个资源,成功应用 {successCount} 个纹理!", "确定");
    }
}

// 补充笔记:
// 1. 纹理类型(TextureImporterType)常用值:
//    - Sprite:UI精灵、2D纹理
//    - Texture:场景纹理、3D纹理
//    - NormalMap:法线贴图(需单独设置normalmap参数)
// 2. 压缩格式(TextureImporterFormat):
//    - Automatic:自动适配当前平台(推荐)
//    - RGBA32:无压缩(清晰,占用内存大)
//    - ETC2_RGBA8:移动平台推荐(Android/iOS通用)
// 3. 注意:UI纹理建议设置为Sprite,关闭mipmap,wrapMode设为Clamp

2. 模型(Model)导入设置脚本

对应导入器:ModelImporter,核心控制模型的缩放、旋转、动画、材质、骨骼等导入参数。

常用场景:批量导入模型(如角色、场景道具),统一模型缩放、剔除无用动画、分离材质。

using UnityEditor;
using UnityEngine;

/// <summary>
/// 模型导入设置笔记(批量处理模型,统一规范)
/// </summary>
public class ModelImportSettingTool
{
    // 右键菜单:选中模型,右键 -> 模型导入设置 -> 应用默认配置
    [MenuItem("Assets/模型导入设置/应用默认配置", false, 1)]
    public static void ApplyDefaultModelSettings()
    {
        Object[] selectedObjects = Selection.objects;
        if (selectedObjects == null || selectedObjects.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请选中模型资源!", "确定");
            return;
        }

        foreach (Object obj in selectedObjects)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            // 判断是否是模型资源(模型后缀:.fbx/.obj/.gltf等)
            if (assetPath.EndsWith(".fbx") || assetPath.EndsWith(".obj") || assetPath.EndsWith(".gltf"))
            {
                ModelImporter modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter;
                if (modelImporter != null)
                {
                    // 核心设置(笔记:按需调整,以下是通用默认配置)
                    // 1. 模型基础设置
                    modelImporter.importScale = 1.0f; // 导入缩放(统一为1,避免模型大小不一)
                    modelImporter.importRotation = new Vector3(0, 0, 0); // 导入旋转(统一朝向)
                    modelImporter.importPosition = Vector3.zero; // 导入位置(原点)
                    modelImporter.useFileScale = false; // 不使用文件自身缩放

                    // 2. 网格设置
                    modelImporter.meshCompression = ModelImporterMeshCompression.Medium; // 网格压缩(中等,平衡质量和大小)
                    modelImporter.optimizeMesh = true; // 优化网格(减少面数,提升性能)
                    modelImporter.generateSecondaryUV = true; // 生成二次UV(用于光照贴图)

                    // 3. 动画设置(无动画的模型可关闭)
                    modelImporter.importAnimation = false; // 不导入动画(按需开启)
                    modelImporter.animationType = ModelImporterAnimationType.None; // 动画类型(无动画)

                    // 4. 材质设置
                    modelImporter.materialImportMode = ModelImporterMaterialImportMode.None; // 不自动导入材质(避免生成多余材质)
                    modelImporter.materialName = ModelImporterMaterialName.BasedOnModelNameAndMaterialName; // 材质命名规则

                    // 5. 其他设置
                    modelImporter.castShadows = ShadowCastingMode.On; // 投射阴影
                    modelImporter.receiveShadows = true; // 接收阴影
                    modelImporter.importNormals = ModelImporterNormals.Calculate; // 计算法线

                    // 保存并重新导入
                    modelImporter.SaveAndReimport();
                }
            }
        }

        EditorUtility.DisplayDialog("完成", "模型默认配置已应用!", "确定");
    }

    // 补充:单独设置模型动画导入(按需调用)
    [MenuItem("Assets/模型导入设置/导入动画", false, 2)]
    public static void ImportModelAnimation()
    {
        Object[] selectedObjects = Selection.objects;
        foreach (Object obj in selectedObjects)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            if (assetPath.EndsWith(".fbx"))
            {
                ModelImporter modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter;
                if (modelImporter != null)
                {
                    modelImporter.importAnimation = true;
                    modelImporter.animationType = ModelImporterAnimationType.Humanoid; // 人形动画(角色用)
                    modelImporter.autoGenerateAvatar = true; // 自动生成人形骨骼
                    modelImporter.SaveAndReimport();
                }
            }
        }
    }

    // 笔记要点:
    // 1. 模型缩放:统一设置为1,避免不同模型大小差异过大
    // 2. 动画导入:角色模型设为Humanoid,道具模型设为None
    // 3. 材质导入:建议关闭自动导入,手动创建材质赋值,避免冗余
    // 4. 网格压缩:移动端建议Medium/High,PC端可设为Low
    // 5. 二次UV:场景模型必须开启,否则光照贴图会出现拉伸
}

// 额外:批量修改模型材质路径(如果模型材质路径错误)
public class ModelMaterialPathTool : Editor
{
    [MenuItem("工具/批量修复模型材质路径")]
    public static void FixModelMaterialPath()
    {
        string materialRootPath = "Assets/Materials/"; // 材质根路径
        Object[] selectedModels = Selection.objects;
        foreach (Object model in selectedModels)
        {
            string modelPath = AssetDatabase.GetAssetPath(model);
            ModelImporter modelImporter = AssetImporter.GetAtPath(modelPath) as ModelImporter;
            if (modelImporter != null)
            {
                // 获取模型的所有材质
                Material[] materials = modelImporter.GetMaterials();
                for (int i = 0; i < materials.Length; i++)
                {
                    // 重新赋值材质(根据材质名查找)
                    Material newMat = AssetDatabase.LoadAssetAtPath<Material>(materialRootPath + materials[i].name + ".mat");
                    if (newMat != null)
                    {
                        materials[i] = newMat;
                    }
                }
                // 应用材质修改
                modelImporter.SetMaterials(materials);
                modelImporter.SaveAndReimport();
            }
        }
    }
}

3. 音频(Audio)导入设置脚本

对应导入器:AudioImporter,核心控制音频的压缩格式、采样率、循环、3D音效等参数。

常用场景:批量设置背景音乐、音效的压缩格式,区分2D/3D音效。

using UnityEditor;
using UnityEngine;

/// <summary>
/// 音频导入设置笔记(批量处理音频资源)
/// </summary>
public class AudioImportSettingTool
{
    // 批量设置背景音乐(2D,无3D音效,低压缩)
    [MenuItem("Assets/音频导入设置/设置为背景音乐")]
    public static void SetAsBGM()
    {
        ApplyAudioSettings(AudioImporterFormat.MPEG, 44100, false, true);
    }

    // 批量设置音效(2D,高压缩,小体积)
    [MenuItem("Assets/音频导入设置/设置为音效")]
    public static void SetAsSoundEffect()
    {
        ApplyAudioSettings(AudioImporterFormat.Vorbis, 22050, false, false);
    }

    // 批量设置3D音效(如角色脚步声、环境音)
    [MenuItem("Assets/音频导入设置/设置为3D音效")]
    public static void SetAs3DSound()
    {
        ApplyAudioSettings(AudioImporterFormat.Vorbis, 22050, true, false);
    }

    /// <summary>
    /// 通用音频导入设置方法
    /// </summary>
    /// <param name="format">压缩格式</param>
    /// <param name="sampleRate">采样率</param>
    /// <param name="is3D">是否3D音效</param>
    /// <param name="loop">是否循环</param>
    private static void ApplyAudioSettings(AudioImporterFormat format, int sampleRate, bool is3D, bool loop)
    {
        Object[] selectedAudios = Selection.objects;
        if (selectedAudios == null || selectedAudios.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请选中音频资源!", "确定");
            return;
        }

        int count = 0;
        foreach (Object obj in selectedAudios)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            // 判断是否是音频资源(后缀:.mp3/.wav/.ogg)
            if (assetPath.EndsWith(".mp3") || assetPath.EndsWith(".wav") || assetPath.EndsWith(".ogg"))
            {
                AudioImporter audioImporter = AssetImporter.GetAtPath(assetPath) as AudioImporter;
                if (audioImporter != null)
                {
                    // 核心设置
                    audioImporter.format = format; // 压缩格式
                    audioImporter.sampleRateOverride = sampleRate; // 采样率(越低体积越小)
                    audioImporter.forceToMono = false; // 不强制单声道(背景音乐建议立体声)
                    audioImporter.loadInBackground = true; // 后台加载(避免卡顿)

                    // 3D音效设置
                    AudioImporterSampleSettings sampleSettings = audioImporter.defaultSampleSettings;
                    sampleSettings.spatialBlend = is3D ? 1.0f : 0.0f; // 0=2D,1=3D
                    sampleSettings.loop = loop; // 是否循环(背景音乐循环,音效不循环)
                    audioImporter.defaultSampleSettings = sampleSettings;

                    // 保存并重新导入
                    audioImporter.SaveAndReimport();
                    count++;
                }
            }
        }

        EditorUtility.DisplayDialog("完成", $"共处理 {count} 个音频资源!", "确定");
    }

    // 笔记要点:
    // 1. 压缩格式选择:
    //    - 背景音乐:MPEG(mp3格式,压缩比高,音质较好)
    //    - 音效:Vorbis(ogg格式,体积小,适合大量音效)
    // 2. 采样率:
    //    - 背景音乐:44100Hz(标准音质)
    //    - 音效:22050Hz(足够清晰,体积更小)
    // 3. 3D音效:spatialBlend设为1,配合AudioSource的3D设置使用
    // 4. 循环:背景音乐设为true,音效设为false
    // 5. 注意:wav格式无压缩,建议转为mp3/ogg,减少包体大小
}

4. 精灵图集(Sprite Atlas)导入设置脚本

对应导入器:SpriteAtlasImporter,核心控制图集的打包规则、压缩格式、图集大小等。

常用场景:批量创建精灵图集、修改图集打包参数,优化UI渲染性能。

using UnityEditor;
using UnityEngine.U2D;

/// <summary>
/// 精灵图集导入设置笔记
/// </summary>
public class SpriteAtlasImportSettingTool : EditorWindow
{
    [MenuItem("工具/精灵图集设置")]
    public static void OpenAtlasWindow()
    {
        GetWindow<SpriteAtlasImportSettingTool>("精灵图集设置");
    }

    private int atlasSize = 2048; // 图集尺寸
    private TextureImporterFormat atlasFormat = TextureImporterFormat.Automatic; // 压缩格式
    private bool allowRotation = true; // 允许精灵旋转(节省空间)
    private bool allowTightPacking = true; // 紧密打包

    private void OnGUI()
    {
        atlasSize = EditorGUILayout.IntField("图集尺寸", atlasSize);
        atlasFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup("压缩格式", atlasFormat);
        allowRotation = EditorGUILayout.Toggle("允许精灵旋转", allowRotation);
        allowTightPacking = EditorGUILayout.Toggle("紧密打包", allowTightPacking);

        if (GUILayout.Button("应用选中图集设置"))
        {
            ApplyAtlasSettings();
        }

        if (GUILayout.Button("批量创建精灵图集"))
        {
            CreateSpriteAtlas();
        }
    }

    /// <summary>
    /// 应用选中图集的设置
    /// </summary>
    private void ApplyAtlasSettings()
    {
        Object[] selectedAtlases = Selection.objects;
        if (selectedAtlases == null || selectedAtlases.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请选中精灵图集!", "确定");
            return;
        }

        foreach (Object obj in selectedAtlases)
        {
            if (obj is SpriteAtlas atlas)
            {
                string assetPath = AssetDatabase.GetAssetPath(atlas);
                SpriteAtlasImporter atlasImporter = AssetImporter.GetAtPath(assetPath) as SpriteAtlasImporter;
                if (atlasImporter != null)
                {
                    // 核心设置
                    atlasImporter.textureSettings.format = atlasFormat; // 压缩格式
                    atlasImporter.textureSettings.maxTextureSize = atlasSize; // 图集尺寸
                    atlasImporter.packingSettings.allowRotation = allowRotation; // 允许旋转
                    atlasImporter.packingSettings.allowTightPacking = allowTightPacking; // 紧密打包
                    atlasImporter.packingSettings.padding = 2; // 精灵之间的间距(避免拉伸)

                    // 保存并重新导入
                    atlasImporter.SaveAndReimport();
                }
            }
        }

        EditorUtility.DisplayDialog("完成", "图集设置已应用!", "确定");
    }

    /// <summary>
    /// 批量创建精灵图集(将选中的精灵打包成一个图集)
    /// </summary>
    private void CreateSpriteAtlas()
    {
        Object[] selectedSprites = Selection.objects;
        if (selectedSprites == null || selectedSprites.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请选中精灵资源!", "确定");
            return;
        }

        // 创建精灵图集
        SpriteAtlas atlas = new SpriteAtlas();
        // 设置图集参数
        atlas.SetIncludeInBuild(true); // 打包时包含该图集
        // 添加选中的精灵到图集
        Sprite[] sprites = new Sprite[selectedSprites.Length];
        for (int i = 0; i < selectedSprites.Length; i++)
        {
            if (selectedSprites[i] is Sprite sprite)
            {
                sprites[i] = sprite;
            }
        }
        atlas.Add(sprites);

        // 保存图集到指定路径
        string savePath = "Assets/SpriteAtlases/NewAtlas.spriteatlas";
        AssetDatabase.CreateAsset(atlas, savePath);
        AssetDatabase.Refresh();

        // 应用图集设置
        SpriteAtlasImporter atlasImporter = AssetImporter.GetAtPath(savePath) as SpriteAtlasImporter;
        if (atlasImporter != null)
        {
            atlasImporter.textureSettings.format = atlasFormat;
            atlasImporter.textureSettings.maxTextureSize = atlasSize;
            atlasImporter.packingSettings.allowRotation = allowRotation;
            atlasImporter.packingSettings.allowTightPacking = allowTightPacking;
            atlasImporter.SaveAndReimport();
        }

        EditorUtility.DisplayDialog("完成", "精灵图集创建成功!", "确定");
    }

    // 笔记要点:
    // 1. 图集尺寸:建议为2的幂次方(如1024、2048、4096),避免渲染异常
    // 2. 间距(padding):建议设为2-4,防止精灵边缘拉伸、模糊
    // 3. 紧密打包:开启后节省空间,但可能增加打包时间
    // 4. 压缩格式:与纹理一致,UI图集建议用ETC2_RGBA8(移动平台)
    // 5. 注意:图集创建后,原精灵可删除(但建议保留备份,便于后续修改)
}

三、自动触发导入设置(进阶)

无需手动点击按钮,当资源导入(或修改)时,自动应用预设的导入设置,适用于项目规范强制统一。

核心:继承 AssetPostprocessor,重写对应资源的导入回调方法。

using UnityEditor;
using UnityEngine;

/// <summary>
/// 自动导入设置笔记(资源导入时自动应用配置)
/// </summary>
public class AutoImportSetting : AssetPostprocessor
{
    // 1. 纹理导入完成后,自动应用设置
    private void OnPostprocessTexture(Texture2D texture)
    {
        // 获取纹理导入器
        TextureImporter textureImporter = assetImporter as TextureImporter;
        if (textureImporter == null) return;

        // 根据纹理路径判断类型(如UI纹理、场景纹理)
        string assetPath = assetPath.ToLower();
        if (assetPath.Contains("ui"))
        {
            // UI纹理设置
            textureImporter.textureType = TextureImporterType.Sprite;
            textureImporter.isReadable = false;
            textureImporter.mipmapEnabled = false;
            textureImporter.wrapMode = TextureWrapMode.Clamp;
            textureImporter.filterMode = FilterMode.Bilinear;
            textureImporter.textureFormat = TextureImporterFormat.Automatic;
        }
        else if (assetPath.Contains("scene"))
        {
            // 场景纹理设置
            textureImporter.textureType = TextureImporterType.Texture;
            textureImporter.mipmapEnabled = true;
            textureImporter.wrapMode = TextureWrapMode.Repeat;
            textureImporter.textureFormat = TextureImporterFormat.Automatic;
        }

        // 无需调用SaveAndReimport(),OnPostprocessTexture会自动保存
    }

    // 2. 模型导入完成后,自动应用设置
    private void OnPostprocessModel(GameObject model)
    {
        ModelImporter modelImporter = assetImporter as ModelImporter;
        if (modelImporter == null) return;

        // 统一模型设置
        modelImporter.importScale = 1.0f;
        modelImporter.optimizeMesh = true;
        modelImporter.generateSecondaryUV = true;
        modelImporter.importAnimation = false;
        modelImporter.materialImportMode = ModelImporterMaterialImportMode.None;
    }

    // 3. 音频导入完成后,自动应用设置
    private void OnPostprocessAudio(AudioClip clip)
    {
        AudioImporter audioImporter = assetImporter as AudioImporter;
        if (audioImporter == null) return;

        string assetPath = assetPath.ToLower();
        if (assetPath.Contains("bgm"))
        {
            // 背景音乐设置
            audioImporter.format = AudioImporterFormat.MPEG;
            audioImporter.sampleRateOverride = 44100;
            audioImporter.defaultSampleSettings.loop = true;
            audioImporter.defaultSampleSettings.spatialBlend = 0;
        }
        else if (assetPath.Contains("sound"))
        {
            // 音效设置
            audioImporter.format = AudioImporterFormat.Vorbis;
            audioImporter.sampleRateOverride = 22050;
            audioImporter.defaultSampleSettings.loop = false;
            audioImporter.defaultSampleSettings.spatialBlend = 0;
        }
    }

    // 笔记要点:
    // 1. 该脚本无需手动执行,放在Editor文件夹下即可自动生效
    // 2. assetPath:当前导入资源的路径(可用于区分不同类型的资源)
    // 3. OnPostprocessXXX回调:对应不同资源的导入完成事件
    // 4. 适用场景:项目规范严格,避免手动修改导入设置导致的错误
    // 5. 注意:如果手动修改了导入设置,下次资源重新导入(如修改外部文件),会被自动设置覆盖
}

四、通用工具类(常用封装,必记)

封装常用方法,减少重复代码,方便后续调用。

using UnityEditor;
using UnityEngine;

/// <summary>
/// 资源导入设置通用工具笔记(封装常用方法)
/// </summary>
public static class ImportSettingUtility
{
    /// <summary>
    /// 获取指定路径的资源导入器
    /// </summary>
    /// <param name="assetPath">资源路径(Assets/开头)</param>
    /// <returns>AssetImporter</returns>
    public static AssetImporter GetAssetImporter(string assetPath)
    {
        if (string.IsNullOrEmpty(assetPath) || !assetPath.StartsWith("Assets/"))
        {
            Debug.LogError("资源路径无效!必须以Assets/开头");
            return null;
        }
        return AssetImporter.GetAtPath(assetPath);
    }

    /// <summary>
    /// 批量重新导入选中资源
    /// </summary>
    [MenuItem("工具/批量重新导入选中资源")]
    public static void ReimportSelectedAssets()
    {
        Object[] selectedObjects = Selection.objects;
        if (selectedObjects == null || selectedObjects.Length == 0)
        {
            EditorUtility.DisplayDialog("提示", "请选中资源!", "确定");
            return;
        }

        foreach (Object obj in selectedObjects)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
        }

        EditorUtility.DisplayDialog("完成", "选中资源已重新导入!", "确定");
    }

    /// <summary>
    /// 批量设置资源的AssetBundle名称
    /// </summary>
    /// <param name="bundleName">AssetBundle名称</param>
    [MenuItem("工具/批量设置AssetBundle名称")]
    public static void SetAssetBundleName()
    {
        string bundleName = EditorGUILayout.TextField("请输入AssetBundle名称:");
        if (string.IsNullOrEmpty(bundleName))
        {
            EditorUtility.DisplayDialog("提示", "请输入AssetBundle名称!", "确定");
            return;
        }

        Object[] selectedObjects = Selection.objects;
        foreach (Object obj in selectedObjects)
        {
            string assetPath = AssetDatabase.GetAssetPath(obj);
            AssetImporter importer = GetAssetImporter(assetPath);
            if (importer != null)
            {
                importer.SetAssetBundleNameAndVariant(bundleName, "");
                importer.SaveAndReimport();
            }
        }

        EditorUtility.DisplayDialog("完成", "AssetBundle名称已设置!", "确定");
    }

    // 笔记要点:
    // 1. 封装的方法可在其他脚本中直接调用,如 ImportSettingUtility.GetAssetImporter()
    // 2. 重新导入资源:用于修改导入设置后,强制刷新资源
    // 3. AssetBundle设置:用于资源打包,批量设置统一的包名
}

五、注意事项(重点,必记)

    1. 脚本存放:所有导入设置脚本,必须放在 Editor 文件夹下(可嵌套子文件夹),否则Editor API无法访问,脚本无效。
    1. 路径规范:资源路径必须以 "Assets/" 开头,区分大小写(如 "Assets/Textures" 不能写成 "assets/textures"),否则无法获取导入器。
    1. 保存生效:所有修改导入设置的操作,必须调用 SaveAndReimport() 方法,否则修改不会生效(自动触发的OnPostprocessXXX除外)。
    1. 版本兼容:不同Unity版本的导入器API可能有差异(如Unity 2022与2019),脚本编写时需注意当前使用的Unity版本,避免API过时。
    1. 性能影响:批量处理大量资源(如几百个纹理、模型)时,会占用编辑器性能,建议分批次处理,避免编辑器卡顿。
    1. 备份资源:修改导入设置前,建议备份原始资源,避免误操作导致资源损坏(尤其是模型、动画资源)。
    1. 发布排除:导入设置脚本仅在Editor模式生效,发布游戏时,Unity会自动剔除Editor文件夹下的所有脚本,不会影响包体大小和运行性能。
    1. 权限问题:如果脚本无法执行,检查是否有足够的权限(如只读文件无法修改导入设置),或重启Unity尝试。

六、总结(核心要点)

  1. 核心逻辑:通过 AssetImporter 及其子类,获取资源导入器,修改参数,保存并重新导入。

  2. 核心场景:批量处理资源、统一项目规范、自动化导入配置,减少重复手动操作。

  3. 关键分类:纹理、模型、音频、精灵图集,对应不同的导入器子类,需针对性编写脚本。

  4. 进阶技巧:使用 AssetPostprocessor 实现自动导入设置,使用通用工具类封装常用方法,提升开发效率。

  5. 避坑重点:脚本存放路径、资源路径规范、SaveAndReimport()调用、版本兼容。

(注:文档部分内容由 AI 生成)