Unity资源导入时,自动设置AssetBundle name

本文介绍如何在Unity中导入资源时,自动为AssetBundle指定name,例如 Scenes/ui_login.unity 导入后,AssetBundle name设为 scenes/ui_login。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

资源:Assets/GameContent/Scenes/ui_login.unity

AssetBundle name自动设置为: scenes/ui_login

using UnityEditor;

public class AssetsImportMgr : AssetPostprocessor
{
    static void OnPostprocessAllAssets(          
       string[] importedAssets,
       string[] deletedAssets,
       string[] movedAssets,
       string[] movedFromAssetPaths)
    {
        autoSetAssetBundleName(importedAssets);
    }

    static string[] ResSuffix = { ".unity", ".prefab" };
    static string RootDir = "GameContent";

    /// <summary>
    /// 资源导入时自动设置AssetBundle name
    /// </summary>
    /// <param name="importedAssets"></param>
    static void autoSetAssetBundleName(string[] importedAssets)
    {
        foreach (var path in importedAssets)
        {
            //是否GameContent目录下
            int firstIndex = path.IndexOf(RootDir) + RootDir.Length + 1;
            if(firstIndex == -1)
                continue;

            //后缀是否对
            int secondIndex = -1;
            string pathLower = path.ToLower();
            for (int i = 0; i < ResSuffix.Length; i++)
            {
                if (pathLower.EndsWith(ResSuffix[i]))
                {
                    secondIndex = pathLower.LastIndexOf(ResSuffix[i]);
                    break;
                }
            }
            if (secondIndex == -1)
                continue;

            string bundleName = string.Empty;
            if (secondIndex >= 0)
                bundleName = pathLower.Substring(firstIndex, secondIndex - firstIndex);

            //设置name
            AssetImporter importer = AssetImporter.GetAtPath(path);
            if(importer != null)
            {
                importer.assetBundleName = bundleName;
                importer.assetBundleVariant = ""; 
            }

        }
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值