public static void BuildAssetBundleFromResourcesSelection()
    {
        Object[] selection  = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
        string[] assetNames = new string[selection.Length];
        Debug.Log("Creating asset bundle containing: ");
        for (int i = 0; i < selection.Length; i++)
        {
            string fullPath = AssetDatabase.GetAssetPath(selection[i]);
            int    idx      = fullPath.LastIndexOf('.');
            if (idx > 0)
            {
                fullPath = fullPath.Remove(idx);
            }
            assetNames[i] = fullPath.Substring(fullPath.IndexOf("Resources/") + "Resources/".Length);
            Debug.Log(assetNames[i]);
        }

        if (selection.Length > 0)
        {
            string savePath = EditorUtility.SaveFilePanel("Save Resource", "", "New Resource", "assetbundle");
            if (savePath.Length != 0)
            {
                BuildPipeline.BuildAssetBundleExplicitAssetNames(selection, assetNames, savePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets,
                                                                 EditorUserBuildSettings.activeBuildTarget);
            }
        }
    }
Example #2
0
    public void Build(string p, Dictionary <string, AssetBundleFile> allAb)
    {
        if (!path.Contains("Assets/"))
        {
            return;
        }

        var abPath = path.Replace("/", "_");
        var fName  = Path.Combine(p, abPath);

        BuildPipeline.PushAssetDependencies();
        foreach (var d in dependency)
        {
            allAb[d].TempBuild();
        }
        //是否收集脚本
        BuildPipeline.PushAssetDependencies();
        BuildPipeline.BuildAssetBundleExplicitAssetNames(objs, names, fName, BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneOSXIntel64);
        BuildPipeline.PopAssetDependencies();
        BuildPipeline.PopAssetDependencies();

        using (var m = MD5.Create()){
            using (var stream = File.OpenRead(fName)) {
                var h = m.ComputeHash(stream);
                //md5 = System.BitConverter.ToString(h).Replace("-", "");
                md5 = System.Convert.ToBase64String(h);
            }
        }
        buildYet = true;
    }
Example #3
0
    public static void BuildBundleForCurrentPlatforms(AssetBundleListing listing)
    {
        var curPlats = Settings.GetPlatformsForCurrentBuildTarget(EditorUserBuildSettings.activeBuildTarget);

        foreach (BundlePlatform plat in curPlats)
        {
            string        path = Settings.bundleDirectoryRelativeToProjectFolder;
            DirectoryInfo di   = new DirectoryInfo(path);
            path += "/" + listing.name + "_" + plat.name + ".unity3d";
            if (!di.Exists)
            {
                di.Create();
            }
            BuildAssetBundleOptions babOpts = BuildAssetBundleOptions.CompleteAssets;
            if (listing.gatherDependencies)
            {
                babOpts |= BuildAssetBundleOptions.CollectDependencies;
            }
            if (!listing.compressed)
            {
                babOpts |= BuildAssetBundleOptions.UncompressedAssetBundle;
            }
            var files = listing.GetAssetsForPlatform(plat.name);
            var names = listing.GetNamesForPlatform(plat.name);
            BuildPipeline.BuildAssetBundleExplicitAssetNames(files.ToArray(), names.ToArray(), path, babOpts, plat.unityBuildTarget);
        }
    }
Example #4
0
    static void BuildWithExplicitAssetNames()
    {
        Debug.Log("Selection.activeObject=" + Selection.activeObject.name);

        for (int i = 0; i < Selection.objects.Length; ++i)
        {
            Debug.Log("Selection.objects[ i ]=" + Selection.objects[i]);
            Debug.Log("Selection.objects[ i ].GetType()=" + Selection.objects[i].GetType());
        }

        string [] pathes;
        RetrieveFilePath(Selection.objects, out pathes);

        for (int i = 0; i < pathes.Length; ++i)
        {
            Debug.Log("pathes[ i ]=" + pathes[i]);
        }


        BuildPipeline.BuildAssetBundleExplicitAssetNames(
            Selection.objects,
            pathes,
            "BuildWithExplicitAssetNames.unity3d");

        Debug.Log("BuildWithExplicitAssetNames() completed.");
    }
Example #5
0
    public static void BuildAssets(string resources, Object assetObject)
    {
        //DisableRes(true);
        bs.setting = settings;
        BuildTarget bt   = activeBuildTarget;
        var         file = resources + ".unity3d" + bs.platformPrefix2;
        var         path = AssetDatabase.GetAssetPath(assetObject);

        var asss  = new List <Object>();
        var asss2 = new List <string>();

        foreach (var f in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
        {
            var asset = AssetDatabase.LoadMainAssetAtPath(f);
            if (asset != null)
            {
                asss.Add(asset);
                int startIndex = path.Length + 1;
                var str        = f.Substring(startIndex, f.LastIndexOf('.') - startIndex).Replace('\\', '/');
                asss2.Add("@" + str);
            }
        }

        BuildPipeline.BuildAssetBundleExplicitAssetNames(asss.ToArray(), asss2.ToArray(), outputFolder + file, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, bt);
        //DisableRes(false);
    }
Example #6
0
    //只需要生成依赖文件的ID即可 不需要组件 除非使用了对象的组件
    //不需要收集依赖
    public void TempBuild()
    {
        var abPath   = path.Replace("/", "_");
        var tempPath = Path.Combine(Application.dataPath, "../TempAb");
        var fName    = Path.Combine(tempPath, abPath);

        BuildPipeline.BuildAssetBundleExplicitAssetNames(objs, names, fName, BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.StandaloneOSXIntel64);
    }
Example #7
0
    private static bool BuildSingleBundle(Hashtable bundle, string parent, BundleOptions options)
    {
        string id     = EB.Dot.String("id", bundle, string.Empty);
        string folder = EB.Dot.String("folder", bundle, string.Empty);
        string prefix = EB.Dot.String("prefix", bundle, string.Empty);
        string filter = EB.Dot.String("filter", bundle, string.Empty);

        string targetFolder = Path.Combine(_outFolder, id);

        Directory.CreateDirectory(targetFolder);

        string[] files = Directory.GetFiles(folder, "*.prefab", SearchOption.AllDirectories);
        System.Array.Sort(files);

        bool result = false;

        foreach (string file in files)
        {
            if (!string.IsNullOrEmpty(filter))
            {
                if (!file.Contains(filter))
                {
                    continue;                     // skip asset
                }
            }

            Object obj = AssetDatabase.LoadMainAssetAtPath(file);
            if (obj != null && obj is GameObject)
            {
                string name = obj.name.ToLower().Replace(' ', '_');
                string path = Path.Combine(targetFolder, string.Format("{0}.assetbundle", name));

                var objects = new Object[] { obj };
                var names   = new string[] { AssetName(prefix + obj.name) };
                var paths   = new string[] { PathName(prefix + obj.name) };

                if ((options & BundleOptions.Force) != 0 || CheckDependancies(path, objects))
                {
                    BuildPipeline.PushAssetDependencies();
                    BuildPipeline.BuildAssetBundleExplicitAssetNames(objects, names, path, _bundleOptions, BuildSettings.Target);
                    BuildPipeline.PopAssetDependencies();
                    result = true;
                }

                // add to the toc
                Hashtable toc = new Hashtable();
                toc["paths"]              = paths;
                toc["parent"]             = parent;
                toc["ts"]                 = File.GetLastWriteTime(file).Ticks;
                _bundles[id + "/" + name] = toc;
            }
        }

        return(result);
    }
Example #8
0
    //--------------------------------------------------------------------------------------------
    // 通过 Unity 创建 AssetBundle 文件, 自定义对应的KEY
    static public bool BuildAssetBundleWithNames(Object[] objAry, string [] kAry, string sfile, BuildTarget tgt)
    {
        if ((objAry.Length <= 0) || (objAry.Length > kAry.Length))
        {
            return(false);
        }
        BuildAssetBundleOptions ops = BuildAssetBundleOptions.CollectDependencies;

        //ops |= BuildAssetBundleOptions.UncompressedAssetBundle;
        return(BuildPipeline.BuildAssetBundleExplicitAssetNames(objAry, kAry, sfile, ops, tgt));
    }
    private static void BuildAssetBundleWithoutCollectDependencies(Object[] objs, string[] assetsName, string abPath)
    {
        for (int i = 0; i < assetsName.Length; i++)
        {
            assetsName[i] = EditorFileUtility.GetPathWithoutExt(assetsName[i]);
        }

        BuildPipeline.BuildAssetBundleExplicitAssetNames(objs, assetsName,
                                                         abPath,
                                                         BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle,
                                                         AssetBundleBuildTarget);
    }
Example #10
0
    //构建自己
    public void BuildSelf()
    {
        if (!IsNeedBuild)
        {
            ++BuildPackFromXML.Singleton.SuccPackageCount;
            return;
        }
        IsNeedBuild = false;
        List <UnityEngine.Object> objList  = new List <UnityEngine.Object>();
        List <string>             fileList = new List <string>();

        if (m_type == ENType.enSingle)
        {
            foreach (var item in MyInfo.FileList)
            {
                UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(item);
                if (obj == null)
                {
                    continue;
                }

                objList.Add(obj);
                fileList.Add(item.ToLower());
            }
        }
        else
        {
            IsNeedBuild = false;
            ++BuildPackFromXML.Singleton.SuccPackageCount;
            return;
        }
        if (fileList.Count == 0)
        {
            Debug.Log("build package failed, FileList.Count:" + MyInfo.FileList.Count + ", PackName:" + MyInfo.PackName);
            //空+1
            ++BuildPackFromXML.Singleton.NullPackageCount;
            return;
        }
        string pathname             = BuildPackFromXML.Singleton.PackageDir + MyInfo.PackName;
        BuildAssetBundleOptions ops = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets;

        if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(objList.ToArray(), fileList.ToArray(), pathname, ops, BuildPackFromXML.Singleton.Target))
        {
            Debug.LogError("build package failed! package file path is " + pathname);
            //失败+1
            ++BuildPackFromXML.Singleton.FailPackageCount;
            return;
        }
        Debug.Log("build package succed! package file path is " + pathname);
        //成功+1
        ++BuildPackFromXML.Singleton.SuccPackageCount;
    }
Example #11
0
    static void BundleSelection_Relative()
    {
        string[] paths = new string[Selection.objects.Length];
        for (int i = 0; i < Selection.objects.Length; i++)
        {
            paths[i] = AssetDatabase.GetAssetPath(Selection.objects[i]);
            Debug.Log(paths[i]);
        }

        BuildPipeline.BuildAssetBundleExplicitAssetNames(Selection.objects, paths, "test.assetbundle",
                                                         BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.UncompressedAssetBundle,
                                                         EditorUserBuildSettings.activeBuildTarget);
    }
Example #12
0
        private static void ExpPfbAssetBundle(string terrainDestDir)
        {
            m_groupBundle = PFB_PREFIX + EditorSceneExporter.GetSceneNameWithoutExtension() + BUNDLE_EXT;
            string path = Path.Combine(terrainDestDir, m_groupBundle);
            BuildAssetBundleOptions pfbOp = BuildAssetBundleOptions.CollectDependencies |
                                            BuildAssetBundleOptions.CompleteAssets;

            BuildPipeline.PushAssetDependencies();
            BuildPipeline.BuildAssetBundleExplicitAssetNames(m_groupAssetList.ToArray(),
                                                             m_groupNameList.ToArray(),
                                                             path, pfbOp,
                                                             GOEPack.buildTarget);
            BuildPipeline.PopAssetDependencies();
        }
Example #13
0
    static void DoPackageIcons()

    {
        // Build the resource file from the active selection.

        string [] assetNames = new string[Selection.objects.Length];

        for (int i = 0; i < Selection.objects.Length; ++i)

        {
            assetNames[i] = System.IO.Path.GetFileName(Selection.objects[i].name);
        }

        BuildPipeline.BuildAssetBundleExplicitAssetNames(Selection.objects, assetNames, "Assets/P4Connect/Editor/Icons.pack", BuildAssetBundleOptions.UncompressedAssetBundle);
    }
Example #14
0
    public static void PostExport()
    {
        UnityEngine.Debug.Log(" >>> PostExport Method Started");
        UnityEngine.Debug.Log(" >>> PostExport Process ID: " + Process.GetCurrentProcess().Id);
        UnityEngine.Debug.Log(" >>> PostExport Static Test Value: " + TestValue);

        string asset    = "Assets/Textures/WikiFun_Police_Smiley.png";
        Object assetObj = AssetDatabase.LoadMainAssetAtPath(asset);

        BuildPipeline.BuildAssetBundleExplicitAssetNames(
            new Object[] { assetObj },
            new string[] { "smile" },
            "smile.assetbundle"
            );
        UnityEngine.Debug.Log(" >>> PostExport Method Ended");
    }
Example #15
0
    static void ExportSelection()
    {
        var assets             = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);//Assets/path/to/file
        var assetObjs          = new List <Object> ();
        var explicitAssetNames = new List <string> ();

        foreach (var asset in assets)
        {
            var path = AssetDatabase.GetAssetPath(asset);

            var ext = System.IO.Path.GetExtension(path);
//			var exportName = path.Replace("/", "_").Replace(".", "_");
            var exportName = Path.GetFileName(path);
            exportName = exportName.Substring(0, exportName.IndexOf("."));
            Debug.LogError("Export Name:" + exportName);
            if (ext == ".meta")
            {
                continue;
            }
            try{
                var assetObj = AssetDatabase.LoadAssetAtPath(path, typeof(Object));
                assetObjs.Add(assetObj);
                explicitAssetNames.Add(exportName);
            }catch {
                Debug.LogError("load asset " + path + " fail");
            }
        }

        var filePath   = Application.streamingAssetsPath + "/LuaAssets/";
        var exportPath = Path.Combine(filePath, "lua.unity3d");

        BuildPipeline.PushAssetDependencies();
        BuildPipeline.BuildAssetBundleExplicitAssetNames(assetObjs.ToArray(), explicitAssetNames.ToArray(), exportPath,
                                                         BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.iPhone);
        BuildPipeline.PopAssetDependencies();


//		AssetDatabase.Refresh();//这个要很久
        // AssetBundleが更新されたらローカルキャッシュをクリアする
        Caching.CleanCache();


//			string sourceVersionRoot = App.Path.ExternalResources + "_Version/" + NetworkManager.PLATFORM_SYMBOL;
//			string targetVersionRoot = App.Path.ProjectRoot + "Assets/App/Resources/_Version/" + NetworkManager.PLATFORM_SYMBOL;
//			FileUtil.DeleteFileOrDirectory(targetVersionRoot);
//			FileUtil.CopyFileOrDirectory(sourceVersionRoot, targetVersionRoot);
    }
Example #16
0
        /// <summary>
        /// Saves the object.
        /// </summary>
        /// <returns>
        /// The object.
        /// </returns>
        /// <param name='fileName'>
        /// If set to <c>true</c> file name.
        /// </param>
        /// <param name='assets'>
        /// If set to <c>true</c> assets.
        /// </param>
        /// <param name='assetNames'>
        /// If set to <c>true</c> asset names.
        /// </param>
        /// <param name='mainAsset'>
        /// If set to <c>true</c> main asset.
        /// </param>
        /// <typeparam name='T'>
        /// The 1st type parameter.
        /// </typeparam>
        public static bool SaveObject <T>(string fileName, T[] assets, string[] assetNames, bool mainAsset) where T : Object
        {
            // Objects to be packed in the asset bundle
            List <Object> objsToPack  = new List <Object>();
            List <string> namesToPack = new List <string>();

            // Objects need to be deleted after saving
            List <Object> objsToDestroy = new List <Object>();
            List <Object> objsToDelete  = new List <Object>();

            // Go through all game objects.
            bool hasErr = false;

            for (int i = 0; i < assets.Length; ++i)
            {
                Object obj = AssetShrinker.ShrinkAsset(assetNames[i], assets[i], objsToDestroy, objsToDelete);
                objsToPack.Add(obj);
                namesToPack.Add(assetNames[i]);
            }

            // Save object
            if (!hasErr)
            {
                // Build asset bundle
                Debug.Log(namesToPack.ToArray()[0] + "@@@#" + fileName);
                hasErr = !BuildPipeline.BuildAssetBundleExplicitAssetNames(objsToPack.ToArray(), namesToPack.ToArray(), fileName, BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
            }

            // Delete temp assets.
            foreach (Object obj in objsToDestroy)
            {
                Object.DestroyImmediate(obj);
            }

            foreach (Object obj in objsToDelete)
            {
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(obj));
            }

            if (hasErr)
            {
                Debug.LogErrorFormat("Create asset bundle failed: {0}", fileName);
            }

            return(!hasErr);
        }
Example #17
0
        private void HashETCBuild(string outPath, HashInfo info)
        {
            var files = info.files.Keys.ToList <string>();
            var paths = new string[files.Count];

            for (var i = default(int); i < files.Count; ++i)
            {
                paths[i] = GetPath(files[i]);
            }

            var assets = GetMainAssets(paths);
            var names  = GetAssetNames(files.ToArray());
            var crc    = default(uint);

            Debug.LogFormat("Try build asset : {0}", outPath);
            BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, names, outPath, out crc, mBuildOptions, mBuildtarget);
            Debug.LogFormat("Name : {0} | CRC : {1} | Path : {2}", names, crc, outPath);

            if (crc == default(uint) || !File.Exists(outPath))
            {
                Debug.LogErrorFormat("Failed to create asset : {0}", info.path);
                return;
            }
            else
            {
                var bytes = File.ReadAllBytes(outPath);
                var comps = CLZF2.Compress(bytes);

                var newPath = string.Format("{0}/{1}.lzf", Path.GetDirectoryName(outPath), Path.GetFileNameWithoutExtension(outPath));
                var fs      = new FileStream(newPath, FileMode.Create);

                fs.Write(comps, 0, comps.Length);
                fs.Close();

                var data = MakePatchData(outPath, crc, names);
                var key  = string.Format("{0}/{1}", data.Path, data.Name);

                if (mPatchList.datas.ContainsKey(key))
                {
                    mPatchList.datas.Remove(key);
                }

                mPatchList.AddData(data);
            }
        }
Example #18
0
        /// <summary>
        /// 导出资源包
        /// </summary>
        public static bool ExportRes(ResExportDesc rd, bool compress)
        {
            // 导出
            string pathName = UtilityTools.GenResExportPath(rd.resDir, rd.resName);
            var    names    = new string[] { rd.resName };
            var    assets   = new UnityEngine.Object[] { rd.asset };
            var    options  = BuildAssetBundleOptions.DeterministicAssetBundle;

            if (!compress)
            {
                options |= BuildAssetBundleOptions.UncompressedAssetBundle;
            }
            if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, names, pathName, options, EditorUserBuildSettings.activeBuildTarget))
            {
                Debug.LogErrorFormat("ExportAssetBundle {0} failed!", pathName);
                return(false);
            }

            return(true);
        }
Example #19
0
    private static bool BuildAssetBundle(string[] assetsList, string outputPath)
    {
        // Load all of assets in this bundle
        List <UnityEngine.Object> dependAssets = new List <UnityEngine.Object>();
        List <string>             names        = new List <string>();

        foreach (string assetPath in assetsList)
        {
            UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object));
            if (asset != null)
            {
                dependAssets.Add(asset);
                names.Add(asset.name);
            }
            else
            {
                UnityEngine.Debug.LogError("Cannnot load [" + assetPath + "] as asset object");
            }
        }

        if (dependAssets.Count == 0)
        {
            UnityEngine.Debug.Log(" Try to build empty package : " + outputPath);
            return(true);
        }

        // Build bundle
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9
        return(BuildPipeline.BuildAssetBundle(null,
                                              dependAssets.ToArray(),
                                              outputPath,
                                              (BMDataAccessor.BMConfiger.Compress ? 0 : BuildAssetBundleOptions.UncompressedAssetBundle) | BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.DeterministicAssetBundle,
                                              BuildConfiger.UnityBuildTarget));
#else
        uint crc;
        return(BuildPipeline.BuildAssetBundleExplicitAssetNames(
                   dependAssets.ToArray(),
                   names.ToArray(),
                   outputPath, out crc));
#endif
    }
Example #20
0
    // <summary>
    // 指定フォルダーを指定プラットフォームのAssetBundleを生成する </summary>
    public static void Build(string outPath, string resPath, BuildTarget target)
    {
        if (Directory.Exists(outPath) == false)
        {
            Directory.CreateDirectory(outPath);
        }

        string[] files;
        Object[] assets;
        CreateTargetFileList(Application.dataPath, resPath, out files, out assets);

        {                               // FileListのload test.
            bool msgPackValidflag = false;
            foreach (Object obj in assets)
            {
                if (obj.name == strOutputFileList)
                {
                    TextAsset              msgBin  = obj as TextAsset;
                    ObjectPacker           packerd = new ObjectPacker();
                    SerializeData.FileList flistd  = packerd.Unpack <SerializeData.FileList> (msgBin.bytes);
                    if (flistd.version == fileVersion)
                    {
                        msgPackValidflag = true;
                        break;
                    }
                }
            }
            if (msgPackValidflag == false)
            {
                Debug.Log("ERROR:msgPack valid");
                return;
            }
        }
        Debug.Log(outPath + "/" + resPath + kExtensionAssetBundle);
        BuildAssetBundleOptions opt = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets;

        BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, files, outPath + "/" + resPath + kExtensionAssetBundle, opt, target);
    }
Example #21
0
    static void CreateAssetBunldesEachByEach(string strplatform, BuildTarget platform)
    {
        Caching.CleanCache();

        string SrcListFile = Application.dataPath + "/Editor/ExportList.txt";

        if (!System.IO.File.Exists(SrcListFile))
        {
            return;
        }

        string[]      SrcPaths             = System.IO.File.ReadAllLines(SrcListFile);
        List <string> SrcSubRelDirectories = new List <string>();
        List <string> SrcSubRelFiles       = new List <string> ();

        foreach (string SrcPath in SrcPaths)
        {
            {
                string[] SrcSubDirFullPaths = System.IO.Directory.GetDirectories(Application.dataPath + "/" + OrgFolder + "/" + SrcPath);
                foreach (string SrcSubFullPath in SrcSubDirFullPaths)
                {
                    string SrcSubName    = System.IO.Path.GetFileName(SrcSubFullPath);
                    string SrcSubRelPath = SrcPath + "/" + SrcSubName;
                    SrcSubRelPath = SrcSubRelPath.Replace("\\", "/");
                    SrcSubRelDirectories.Add(SrcSubRelPath);
                }
            }
            foreach (string packext in packexts)
            {
                string[] SrcSubFileFullPaths = System.IO.Directory.GetFiles(Application.dataPath + "/" + OrgFolder + "/" + SrcPath, packext);
                foreach (string SrcSubFullPath in SrcSubFileFullPaths)
                {
                    string SrcSubName    = System.IO.Path.GetFileName(SrcSubFullPath);
                    string SrcSubRelPath = SrcPath + "/" + SrcSubName;
                    SrcSubRelPath = SrcSubRelPath.Replace("\\", "/");
                    SrcSubRelFiles.Add(SrcSubRelPath);
                }
            }
        }

        int nCount = 0;

        foreach (string SrcSubRelPath in SrcSubRelDirectories)
        {
            string[] SrcSubRelPathSplits = SrcSubRelPath.Split('/');

            string DestPackName = "";
            for (int i = 0; i < SrcSubRelPathSplits.Length - 1; i++)
            {
                DestPackName += SrcSubRelPathSplits[i] + "_";
            }
            if (SrcSubRelPathSplits.Length - 1 >= 0)
            {
                DestPackName += SrcSubRelPathSplits[SrcSubRelPathSplits.Length - 1];
            }
            string DestPackagePath = Application.dataPath + "/AssetBundles/" + strplatform + "/" + DestPackName + ".unity3d";
            string DestListPath    = Application.dataPath + "/AssetBundles/" + strplatform + "/" + DestPackName + ".txt";

            string SrcSubFullPath = Application.dataPath + "/" + OrgFolder + "/" + SrcSubRelPath;

            Object[] SelectedAsset      = RecursionGetAllObjectsFromPath(SrcSubFullPath);
            string[] SelectedAssetPaths = GetPathsFromAssets(SelectedAsset);

            if (SelectedAsset == null || SelectedAssetPaths == null ||
                SelectedAsset.Length <= 0 || SelectedAssetPaths.Length <= 0)
            {
                continue;
            }

            StreamWriter sw = new StreamWriter(DestListPath, false);
            sw.WriteLine("#,Path,Type,Package");
            for (int i = 0; i < SelectedAsset.Length; i++)
            {
                Object obj  = SelectedAsset[i];
                string path = SelectedAssetPaths[i];
                sw.WriteLine(i.ToString() + "," + path + "," + obj.GetType().ToString() + "," + DestPackName);
            }
            sw.Close();

            if (BuildPipeline.BuildAssetBundleExplicitAssetNames(SelectedAsset,
                                                                 SelectedAssetPaths,
                                                                 DestPackagePath,
                                                                 BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets,
                                                                 platform))
            {
                Debug.Log("Generate Asset Bundle OK:" + DestPackagePath);
                AssetDatabase.Refresh();
            }
            else
            {
                Debug.Log("Generate Asset Bundle Fail:" + DestPackagePath);
            }

            System.GC.Collect();
            nCount++;

//				float fProgress=(float)nCount/(float)(SrcSubRelPaths.Count);
//				EditorUtility.DisplayProgressBar("Generate Asset Bundles Each by Each","Generate Asset Bundle:"+DestPackName+"...",fProgress);
        }


        foreach (string SrcSubRelPath in SrcSubRelFiles)
        {
            string[] SrcSubRelPathSplits = SrcSubRelPath.Split('/');

            string DestPackName = "";
            for (int i = 0; i < SrcSubRelPathSplits.Length - 1; i++)
            {
                DestPackName += SrcSubRelPathSplits[i] + "_";
            }
            if (SrcSubRelPathSplits.Length - 1 >= 0)
            {
                DestPackName += Path.GetFileNameWithoutExtension(SrcSubRelPathSplits[SrcSubRelPathSplits.Length - 1]);
            }

            string DestPackagePath = Application.dataPath + "/AssetBundles/" + strplatform + "/" + DestPackName + ".unity3d";
            string DestListPath    = Application.dataPath + "/AssetBundles/" + strplatform + "/" + DestPackName + ".txt";

            string SrcSubFullPath = Application.dataPath + "/" + OrgFolder + "/" + SrcSubRelPath;
            if (File.Exists(SrcSubFullPath) == false)
            {
                continue;
            }
            ;

            string srcName = Path.GetFileNameWithoutExtension(SrcSubRelPath);
            string ext     = Path.GetExtension(SrcSubRelPath).ToLower();
            if (ext == ".unity")
            {
                StreamWriter sw = new StreamWriter(DestListPath, false);
                sw.WriteLine("#,Path,Type,Package");
                sw.WriteLine("0" + "," + srcName + "," + "scene" + "," + DestPackName);
                sw.Close();

                bool ret1 = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SrcSubFullPath) != null;
                EditorApplication.Step();
                string TempFullLevel1 = Path.GetDirectoryName(SrcSubFullPath) + "/" + Path.GetFileNameWithoutExtension(SrcSubFullPath) + ".temp";
                File.Copy(SrcSubFullPath, TempFullLevel1, true);
                bool ret2 = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(TempFullLevel1) != null;

                while (true)
                {
                    EditorApplication.Step();
                    if (Path.GetFileNameWithoutExtension(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name) == Path.GetFileNameWithoutExtension(SrcSubFullPath))
                    {
                        break;
                    }
                }
                EditorApplication.Step();

                string scenepath     = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().name;
                string fullscenepath = Path.GetFullPath(scenepath);
                string absfolder     = Path.GetDirectoryName(fullscenepath) + "/" + Path.GetFileNameWithoutExtension(fullscenepath) + "_temp";
                string folder        = Path.GetDirectoryName(scenepath) + "/" + Path.GetFileNameWithoutExtension(scenepath) + "_temp";
                if (Directory.Exists(absfolder))
                {
                    Directory.Delete(absfolder, true);
                }
                Directory.CreateDirectory(absfolder);

                AdorningExporterEx.ExportFun(true, BuildTarget.StandaloneWindows);
                AdorningExporterEx.Clear();
                bool ret3 = UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
                EditorApplication.Step();

                string TempFullLevel2 = absfolder + "/" + Path.GetFileNameWithoutExtension(SrcSubFullPath) + ".unity";
                File.Copy(TempFullLevel1, TempFullLevel2, true);

                string[] levels       = new string[] { TempFullLevel2 };
                string   scenepkgpath = absfolder + "/scene.scenepkg";
                string   msg          = BuildPipeline.BuildStreamedSceneAssetBundle(levels, scenepkgpath, platform);
                {
                    Debug.Log("Generate Scene Pkg OK:" + scenepkgpath);
                }

                bool ret4 = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SrcSubFullPath) != null;
                EditorApplication.Step();
                File.Delete(TempFullLevel2);
                File.Delete(TempFullLevel1);

                //合成一个我们的包
                FileStream   fs = new FileStream(DestPackagePath, FileMode.OpenOrCreate);
                BinaryWriter bw = new BinaryWriter(fs);

                string[] scenepkgs = Directory.GetFiles(absfolder, "*.scenepkg");
                bw.Write(scenepkgs.Length);
                foreach (string scenepkg in scenepkgs)
                {
                    string filename = Path.GetFileNameWithoutExtension(scenepkg);
                    bw.Write(filename);
                    byte[] data = File.ReadAllBytes(scenepkg);
                    bw.Write(data.Length);
                    bw.Write(data);
                    bw.Flush();
                }

                string[] adorningpkgs = Directory.GetFiles(absfolder, "*.adorningpkg");
                bw.Write(adorningpkgs.Length);
                foreach (string adorningpkg in adorningpkgs)
                {
                    string filename = Path.GetFileNameWithoutExtension(adorningpkg);
                    bw.Write(filename);
                    byte[] data = File.ReadAllBytes(adorningpkg);
                    bw.Write(data.Length);
                    bw.Write(data);
                    bw.Flush();
                }

                string[] matpkgs = Directory.GetFiles(absfolder, "*.matpkg");
                bw.Write(matpkgs.Length);
                foreach (string matpkg in matpkgs)
                {
                    string filename = Path.GetFileNameWithoutExtension(matpkg);
                    bw.Write(filename);
                    byte[] data = File.ReadAllBytes(matpkg);
                    bw.Write(data.Length);
                    bw.Write(data);
                    bw.Flush();
                }

                string[] meshpkgs = Directory.GetFiles(absfolder, "*.meshpkg");
                bw.Write(meshpkgs.Length);
                foreach (string meshpkg in meshpkgs)
                {
                    string filename = Path.GetFileNameWithoutExtension(meshpkg);
                    bw.Write(filename);
                    byte[] data = File.ReadAllBytes(meshpkg);
                    bw.Write(data.Length);
                    bw.Write(data);
                    bw.Flush();
                }

                bw.Close();
                fs.Close();
                fs.Dispose();

                if (Directory.Exists(absfolder))
                {
                    Directory.Delete(absfolder, true);
                }

                AssetDatabase.Refresh();
                EditorApplication.Step();

                Debug.Log("Generate Asset Bundle OK:" + DestPackagePath);
            }
            else
            {
                Object   srcAssetObj     = null;
                Object[] srcFilterAssets = AssetDatabase.LoadAllAssetsAtPath(SrcSubFullPath);
                foreach (Object o in srcFilterAssets)
                {
                    if (o.name.ToLower() == srcName.ToLower() && o.GetType() == typeof(GameObject))
                    {
                        srcAssetObj = o;
                        break;
                    }
                }
                if (srcAssetObj == null)
                {
                    continue;
                }
                ;
                string srcAssetPath = Path.GetDirectoryName(SrcSubRelPath) + "/" + Path.GetFileNameWithoutExtension(SrcSubRelPath);

                Object[] SelectedAsset      = new Object[] { srcAssetObj };
                string[] SelectedAssetPaths = new string[] { srcAssetPath };

                if (SelectedAsset == null || SelectedAssetPaths == null ||
                    SelectedAsset.Length <= 0 || SelectedAssetPaths.Length <= 0)
                {
                    continue;
                }

                StreamWriter sw = new StreamWriter(DestListPath, false);
                sw.WriteLine("#,Path,Type,Package");
                for (int i = 0; i < SelectedAsset.Length; i++)
                {
                    Object obj  = SelectedAsset[i];
                    string path = SelectedAssetPaths[i];
                    sw.WriteLine(i.ToString() + "," + path + "," + obj.GetType().ToString() + "," + DestPackName);
                }
                sw.Close();


                if (BuildPipeline.BuildAssetBundleExplicitAssetNames(SelectedAsset,
                                                                     SelectedAssetPaths,
                                                                     DestPackagePath,
                                                                     BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets,
                                                                     platform))
                {
                    Debug.Log("Generate Asset Bundle OK:" + DestPackagePath);
                    AssetDatabase.Refresh();
                }
                else
                {
                    Debug.Log("Generate Asset Bundle Fail:" + DestPackagePath);
                }
            }

            System.GC.Collect();
            nCount++;

            //				float fProgress=(float)nCount/(float)(SrcSubRelPaths.Count);
            //				EditorUtility.DisplayProgressBar("Generate Asset Bundles Each by Each","Generate Asset Bundle:"+DestPackName+"...",fProgress);
        }

        //EditorUtility.ClearProgressBar ();
    }
Example #22
0
    static void BuildOneAssetBundle(string expcur, Dictionary <string, int> objmark, Dictionary <string, List <string> > allobjchild, string path, ref int depcount)
    {
        // 假设已经输出则跳过
        if (objmark.ContainsKey(expcur))
        {
            return;
        }

        List <string> subs = allobjchild[expcur];

        if (subs != null)
        {
            foreach (string sub in subs)
            {
                // 假设已经输出则跳过
                if (objmark.ContainsKey(sub))
                {
                    continue;
                }

                BuildOneAssetBundle(sub, objmark, allobjchild, path, ref depcount);
            }
        }

        objmark[expcur] = 1;

        string asspath = expcur;

        if (string.IsNullOrEmpty(asspath))
        {
            return;
        }

        string guid      = AssetDatabase.AssetPathToGUID(asspath);
        string assetpath = ConvertFileName(Path.GetDirectoryName(asspath));
        string outpath;

        if (asspath != "")
        {
            outpath = path + "/" + assetpath;
        }
        else
        {
            outpath = assetpath;
        }

        Directory.CreateDirectory(outpath);

        //string outfile = Path.Combine(outpath, Path.GetFileNameWithoutExtension(asspath));
        string outfile = outpath + "/" + guid;

        BuildPipeline.PushAssetDependencies();
        depcount++;
        Object realass = AssetDatabase.LoadMainAssetAtPath(expcur);

        if (realass == null)
        {
            return;
        }

        Object[] depobjs = EditorUtility.CollectDependencies(new Object[] { realass });
        Dictionary <string, int> deppathmap = new Dictionary <string, int>();

        foreach (Object depobj in depobjs)
        {
            string deppath = AssetDatabase.GetAssetPath(depobj);

            if (string.IsNullOrEmpty(deppath))
            {
                continue;
            }

            deppathmap[deppath] = 1;
        }

        List <string> realsubs = new List <string>();

        if (subs != null)
        {
            foreach (string sub in subs)
            {
                if (deppathmap.ContainsKey(sub))
                {
                    string realname = ConvertFileName(sub) + ".u3dext";
                    realsubs.Add(realname.ToLower());
                }
            }
        }

        BuildAssetBundleOptions option;

        option  = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.CollectDependencies;
        option |= BuildAssetBundleOptions.UncompressedAssetBundle;

        bool suc = BuildPipeline.BuildAssetBundleExplicitAssetNames(new Object[] { realass }, new string[] { "1" }, outfile,
                                                                    option, ExportAssetBundlesHelper.CurBuildTarget);

        Debug.Log("src file: " + asspath + " " + depcount);

        if (/*realass is MonoScript || */ !deppathmap.ContainsKey(expcur))
        {
            File.Delete(outfile);
        }
        else if (suc)
        {
            // do not compress font
            bool ForceSep = realass is Font;
            bool NeedSep  = false;
            if (!ForceSep)
            {
                FileInfo fi = new FileInfo(outfile);

                if (realass is AudioClip)
                {
                    if (fi.Length > min_audio_clip_bundel_size)
                    {
                        NeedSep = true;
                    }
                }
                else if (fi.Length > min_compress_bundle_size)
                {
                    option = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.CollectDependencies;
                    suc    = BuildPipeline.BuildAssetBundleExplicitAssetNames(new Object[] { realass }, new string[] { "1" }, outfile,
                                                                              option, ExportAssetBundlesHelper.CurBuildTarget);
                    Debug.LogWarning("Big bundle: " + outfile + " Origin Size: " + fi.Length);
                }
            }

            byte[] content  = File.ReadAllBytes(outfile);
            string outfile2 = outpath + "/" + Path.GetFileName(asspath) + ".u3dext";
            _depmap[outfile2.ToLower()] = 1;
            var oldFileInfo = new FileInfo(outfile2);
            if (oldFileInfo.Exists)
            {
                oldFileInfo.IsReadOnly = false;
            }
            using (FileStream fs = File.Open(outfile2, FileMode.Create, FileAccess.Write))
            {
                AssetBundleHeader bh = new AssetBundleHeader();
                bool bDefault        = true;
                if (ForceSep || NeedSep)
                {
                    bh.option |= AssetBundleHeader.BundleOption.SepFile;
                }

                if (realass is Material)
                {
                    bh.specialType = AssetBundleHeader.BundleSpecialType.Material;

                    Material mt = realass as Material;

                    if (mt.shader != null)
                    {
                        bDefault = false;
                        List <string> pnames  = new List <string>();
                        int           nPCount = ShaderUtil.GetPropertyCount(mt.shader);

                        for (int n = 0; n < nPCount; n++)
                        {
                            ShaderUtil.ShaderPropertyType spt = ShaderUtil.GetPropertyType(mt.shader, n);

                            if (spt == ShaderUtil.ShaderPropertyType.TexEnv)
                            {
                                string pn = ShaderUtil.GetPropertyName(mt.shader, n);
                                pnames.Add(pn);
                            }
                        }

                        List <AssetBundleHeader.DepInfo> deplist = new List <AssetBundleHeader.DepInfo>();
                        foreach (var realsub in realsubs)
                        {
                            bool findtex = false;
                            foreach (var texname in pnames)
                            {
                                Texture tex = mt.GetTexture(texname);

                                if (tex)
                                {
                                    string texpath = AssetDatabase.GetAssetPath(tex);

                                    if (!string.IsNullOrEmpty(texpath))
                                    {
                                        string realpath = ConvertFileName(texpath) + ".u3dext";
                                        realpath = realpath.ToLower();

                                        if (realpath == realsub)
                                        {
                                            AssetBundleHeader.DepInfo info = new AssetBundleHeader.DepInfo();
                                            info.name = texname;
                                            info.path = realsub;
                                            deplist.Add(info);
                                            findtex = true;
                                        }
                                    }
                                }
                            }

                            if (!findtex)
                            {
                                AssetBundleHeader.DepInfo info = new AssetBundleHeader.DepInfo();
                                info.name = "";
                                info.path = realsub;
                                deplist.Add(info);
                            }
                        }

                        bh.deps = deplist.ToArray();
                    }
                }
                else if (realass is Texture)
                {
                    bh.option     |= AssetBundleHeader.BundleOption.ManuallyResolve;
                    bh.specialType = AssetBundleHeader.BundleSpecialType.Texture;
                }
                else if (realass is Shader)
                {
                    bh.option |= AssetBundleHeader.BundleOption.DonotRelease;
                }
                else if (realass is MonoScript)
                {
                    bh.option |= AssetBundleHeader.BundleOption.DonotRelease;
                }
                else if (realass is Font)
                {
                    bh.option |= AssetBundleHeader.BundleOption.DonotRelease;
                }

                if (bDefault)
                {
                    bh.deps = new AssetBundleHeader.DepInfo[realsubs.Count];

                    for (int n = 0; n < realsubs.Count; n++)
                    {
                        bh.deps[n].name = "";
                        bh.deps[n].path = realsubs[n];
                    }
                }

                bh.Save(fs);
                fs.Write(content, 0, content.Length);
            }

            File.Delete(outfile);
        }
    }
Example #23
0
    public static void BuildToOneBundle(Object realass, string path, bool recursive)
    {
        if (CheckModify && recursive)
        {
            if (!CheckAssetModify(realass, path, true))
            {
                return;
            }
        }

        int AssetCount = 0;
        List <AssetBundleHeader.DepInfo> ls = new List <AssetBundleHeader.DepInfo>();
        string asspath = AssetDatabase.GetAssetPath(realass);

        if (recursive)
        {
            string[] deppaths = AssetDatabase.GetDependencies(new string[] { asspath });
            Dictionary <string, bool> realdeps = new Dictionary <string, bool>();
            foreach (string realdep in deppaths)
            {
                realdeps[realdep] = true;
            }

            Object[] depobjs = EditorUtility.CollectDependencies(new Object[] { realass });
            BuildPipeline.PushAssetDependencies();
            AssetCount++;

            for (int i = 0; i < depobjs.Length; i++)
            {
                Object dep = depobjs[i];
                if (ReferenceEquals(dep, realass))
                {
                    continue;
                }

                string texpath = AssetDatabase.GetAssetPath(dep);
                if (!realdeps.ContainsKey(texpath))
                {
                    continue;
                }

                if (dep is Texture || dep is Shader || dep is MonoScript || dep is Font)
                {
                    if (!texpath.ToLower().EndsWith(".asset") && !string.IsNullOrEmpty(texpath))
                    {
                        BuildToOneBundle(dep, path, false);
                        AssetBundleHeader.DepInfo info = new AssetBundleHeader.DepInfo();
                        info.name = "";
                        string realname = ConvertFileName(texpath) + ".u3dext";
                        info.path = realname.ToLower();
                        ls.Add(info);
                    }
                }
            }

            BuildPipeline.PushAssetDependencies();
            AssetCount++;
        }

        string assetpath = ConvertFileName(Path.GetDirectoryName(asspath));
        string outpath;

        if (asspath != "")
        {
            outpath = path + "/" + assetpath;
        }
        else
        {
            outpath = assetpath;
        }

        Directory.CreateDirectory(outpath);
        string guid    = AssetDatabase.AssetPathToGUID(asspath);
        string outfile = outpath + "/" + guid;

        BuildAssetBundleOptions option;

        option  = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.CollectDependencies;
        option |= BuildAssetBundleOptions.UncompressedAssetBundle;

        bool suc = BuildPipeline.BuildAssetBundleExplicitAssetNames(new Object[] { realass }, new string[] { "1" }, outfile,
                                                                    option, ExportAssetBundlesHelper.CurBuildTarget);

        // do not compress font
        bool ForceSep = realass is Font;
        bool NeedSep  = false;

        if (suc && !ForceSep)
        {
            FileInfo fi = new FileInfo(outfile);

            if (realass is AudioClip)
            {
                if (fi.Length > min_audio_clip_bundel_size)
                {
                    NeedSep = true;
                }
            }
            else if (fi.Length > min_compress_bundle_size)
            {
                option = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.CollectDependencies;
                suc    = BuildPipeline.BuildAssetBundleExplicitAssetNames(new Object[] { realass }, new string[] { "1" }, outfile,
                                                                          option, ExportAssetBundlesHelper.CurBuildTarget);
                Debug.LogWarning("Big bundle: " + outfile + " Origin Size: " + fi.Length);
            }
        }

        for (int n = 0; n < AssetCount; n++)
        {
            BuildPipeline.PopAssetDependencies();
        }

        if (suc)
        {
            byte[] content  = File.ReadAllBytes(outfile);
            string outfile2 = outpath + "/" + Path.GetFileName(asspath) + ".u3dext";
            using (FileStream fs = File.Open(outfile2, FileMode.Create, FileAccess.Write))
            {
                AssetBundleHeader bh = new AssetBundleHeader();
                if (ForceSep || NeedSep)
                {
                    bh.option |= AssetBundleHeader.BundleOption.SepFile;
                }
                if (realass is Shader || realass is MonoScript || realass is Font)
                {
                    bh.option |= AssetBundleHeader.BundleOption.DonotRelease;
                }
                bh.deps = ls.ToArray();
                bh.Save(fs);
                fs.Write(content, 0, content.Length);
            }

            File.Delete(outfile);
        }
        else
        {
            Debug.LogError("BuildAssetBundleExplicitAssetNames");
        }
    }
    public static void BuildResource()
    {
        AssetDatabase.Refresh();

        //执行依赖性打包

        //资源最大等级
        int maxLevel = allLevelAssets.Count;

        if (maxLevel == 0)
        {
            return;
        }

        //从最低等级开始打包
        for (int level = 1; level <= maxLevel; level++)
        {
            BuildPipeline.PushAssetDependencies();

            //获取不同等级的aaset
            Dictionary <string, AssetUnit> levelAssets = allLevelAssets[level];

            //遍历该等级的所有asset打包
            foreach (KeyValuePair <string, AssetUnit> pair in levelAssets)
            {
                //根据路径获取asset资源
                Object asset = AssetDatabase.LoadMainAssetAtPath(pair.Value.mPath);
                if (null == asset)
                {
                    DebugEx.LogError("load " + pair.Value.mPath + " failed!!!", "BuildResource", true);
                }

                //生成打包保存路径
                string savePath = pair.Value.mPath.Insert(6, assetFilePath) + ResourceCommon.assetbundleFileSuffix;
                BuildCommon.CheckFolder(BuildCommon.getPath(savePath));

                //打包名称去Asset



                //普通资源
                if (pair.Value.mSuffix != "unity")//普通资源
                {
                    string assetName = pair.Value.mPath.Replace("Assets/", "");

                    //资源打包
                    if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(
                            new Object[] { asset }, new string[] { assetName }, savePath, options, buildPlatform))
                    {
                        DebugEx.LogError("build assetbundle " + savePath + " failed!!!", "BuildResource", true);
                    }
                }
                //场景资源,没有依赖场景的
                else
                {
                    AssetDatabase.Refresh();
                    BuildPipeline.PushAssetDependencies();
                    string error = BuildPipeline.BuildStreamedSceneAssetBundle(new string[] { pair.Value.mPath }, savePath, buildPlatform);
                    if (error != "")
                    {
                        DebugEx.LogError(error, "BuildResource", true);
                    }
                    BuildPipeline.PopAssetDependencies();

                    Debug.Log("scene path" + pair.Value.mPath);
                    //pair.Value.mPath
                }
            }
        }

        //popdepency依赖
        for (int level = 1; level <= maxLevel; level++)
        {
            BuildPipeline.PopAssetDependencies();
        }
    }
    private static void BuildAssetBundles()
    {
        ClearAssetBundles();

        // You would probably want to parameterize this part
        Database.Instance.ReadFiles(Application.streamingAssetsPath + "/XML/");

        AssetInfo[]       assetInfos       = Database.Instance.GetEntries <AssetInfo>();
        AssetBundleInfo[] assetBundleInfos = Database.Instance.GetEntries <AssetBundleInfo>();

        // Collect objects and names
        Dictionary <ID, List <Object> > bundleObjects = new Dictionary <ID, List <Object> >();
        Dictionary <ID, List <string> > bundleNames   = new Dictionary <ID, List <string> >();

        foreach (AssetInfo info in assetInfos)
        {
            List <Object> objectList;
            if (!bundleObjects.TryGetValue(info.AssetBundleInfoRef.Entry.DatabaseID, out objectList))
            {
                objectList = new List <Object>();
                bundleObjects.Add(info.AssetBundleInfoRef.Entry.DatabaseID, objectList);
            }

            List <string> nameList;
            if (!bundleNames.TryGetValue(info.AssetBundleInfoRef.Entry.DatabaseID, out nameList))
            {
                nameList = new List <string>();
                bundleNames.Add(info.AssetBundleInfoRef.Entry.DatabaseID, nameList);
            }

            UnityEngine.Object asset = Resources.LoadAssetAtPath <UnityEngine.Object>(info.Path);
            if (asset == null)
            {
                throw new System.Exception("Invalid asset: " + info.Path);
            }

            objectList.Add(asset);
            nameList.Add(info.Path);
        }

        // Build bundles
        foreach (AssetBundleInfo info in assetBundleInfos)
        {
            List <Object> objectList;
            if (!bundleObjects.TryGetValue(info.DatabaseID, out objectList))
            {
                Debug.LogWarning("No objects for bundle: " + info.Name);

                continue;
            }

            List <string> nameList;
            if (!bundleNames.TryGetValue(info.DatabaseID, out nameList))
            {
                throw new System.Exception("No names generated for objects");
            }

            string path = AssetBundlePath + "/" + info.Name + ".unity3d";
            BuildAssetBundleOptions options = (BuildAssetBundleOptions.CollectDependencies |
                                               BuildAssetBundleOptions.CompleteAssets |
                                               BuildAssetBundleOptions.DeterministicAssetBundle);
            BuildTarget target = BuildTarget.WebPlayer;
            if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(objectList.ToArray(),
                                                                  nameList.ToArray(),
                                                                  path,
                                                                  options,
                                                                  target))
            {
                throw new System.Exception("Unable to build asset bundle: " + info.Name);
            }

            AssetDatabase.SaveAssets();

            Debug.Log("Built bundle: " + info.Name);
        }
    }
Example #26
0
    private void PackBundles()
    {
        var referencedObjects = new HashSet <UnityEngine.Object>(_lateProcessor.ReferencedObjects);
        var packedObjects     = new HashSet <UnityEngine.Object>();

        var tempPath = Path.Combine(Path.GetTempPath(), "bundles_" + DateTime.UtcNow.Ticks.ToString());

        BuildUtils.PrepareCleanDirectory(tempPath);

        PushAssetDependencies();
        {
            foreach (var bundleInfo in ScanningUtils.ItemsProcessor(_bundles, "Packing asset bundles", p => Path.GetFileName(p.Name), true))
            {
                Console.WriteLine("Building bundle " + bundleInfo.Name + "...");

                string bundlePath = Path.Combine(tempPath, bundleInfo.Name);                //BuildUtils.GetPathHashString(bundleInfo.Name));

                if (bundleInfo.IsScene)
                {
                    var scenePaths = bundleInfo.AssetsPaths.ToArray();

                    PushAssetDependencies();
                    {
                        string buildResult = BuildPipeline.BuildStreamedSceneAssetBundle(scenePaths,
                                                                                         bundlePath,
                                                                                         _params.Target);
                        if (!String.IsNullOrEmpty(buildResult))
                        {
                            throw new UnityException(buildResult);
                        }
                    }
                    PopAssetDependencies();

                    // Find which assets were packed
                    var packedDependencies = new HashSet <UnityEngine.Object>();
                    foreach (var scenePath in scenePaths)
                    {
                        Debug.Log(scenePath);
                        EditorApplication.OpenScene(scenePath);
                        packedDependencies.UnionWith(ScanningUtils.ScanCurrentSceneAssets());
                        packedDependencies.ExceptWith(packedObjects);
                    }

                    bundleInfo.Dependencies = packedDependencies.ToList();

                    var hash = GetHashForBuildAssets(scenePaths.Concat(BuildUtils.GetAssetPathsForObjects(packedDependencies)));


                    int bundleLevel = _bundleLevelDataBase.GetBundleLevel(bundleInfo.Name);
                    bundleInfo.Data = _bundlesDatabaseBuilder.AddSceneBundle(bundleInfo.Name, hash, bundleLevel,
                                                                             scenePaths.Select(p => Path.GetFileNameWithoutExtension(p)).ToArray(),
                                                                             bundlePath);
                }
                else
                {
                    // Add only the main asset + any late referenced asset

                    var mainObjects     = bundleInfo.AssetsPaths.Select(p => AssetDatabase.LoadMainAssetAtPath(p));
                    var representations = bundleInfo.AssetsPaths.SelectMany(p => AssetDatabase.LoadAllAssetRepresentationsAtPath(p));
                    var objects         = mainObjects.Concat(representations.Where(o => referencedObjects.Contains(o))).ToArray();

                    var assetIds = objects.Select(o => AssetId.FromObject(o)).ToArray();


                    foreach (var obj in objects)
                    {
                        string assetPath = AssetDatabase.GetAssetPath(obj);
                        string guid      = AssetDatabase.AssetPathToGUID(assetPath);
                        Console.WriteLine("path: " + assetPath + "   guid:" + guid);
                    }


                    if (bundleInfo.Isolate)
                    {
                        PushAssetDependencies();
                    }
                    {
                        if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(objects, assetIds, bundlePath,
                                                                              BuildAssetBundleOptions.CompleteAssets |
                                                                              BuildAssetBundleOptions.CollectDependencies |
                                                                              BuildAssetBundleOptions.DeterministicAssetBundle,
                                                                              _params.Target))
                        {
                            throw new UnityException("Error building bundle " + bundleInfo.Name);
                        }
                    }
                    if (bundleInfo.Isolate)
                    {
                        PopAssetDependencies();
                    }

                    // Find which assets were packed
                    var packedDependencies = new HashSet <UnityEngine.Object>(EditorUtility.CollectDependencies(objects.ToArray()));
                    packedDependencies.ExceptWith(packedObjects);
                    bundleInfo.Dependencies = packedDependencies.ToList();
                    if (!bundleInfo.Isolate)
                    {
                        packedObjects.UnionWith(packedDependencies);
                    }

                    var hash        = GetHashForBuildAssets(BuildUtils.GetAssetPathsForObjects(packedDependencies));
                    int bundleLevel = _bundleLevelDataBase.GetBundleLevel(bundleInfo.Name);
                    bundleInfo.Data = _bundlesDatabaseBuilder.AddBundle(bundleInfo.Name, hash, bundleLevel, bundlePath, assetIds.ToList());

                    foreach (var obj in objects)
                    {
                        referencedObjects.Remove(obj);
                    }
                }
            }
        }
        PopAssetDependencies();

        // Move to right destination
        Directory.CreateDirectory(_params.BundlesLocation);
        _bundlesPath = Path.Combine(_params.BundlesLocation, _bundlesDatabaseBuilder.Database.Id);
        FileUtil.DeleteFileOrDirectory(_bundlesPath);
        FileUtil.MoveFileOrDirectory(tempPath, _bundlesPath);

        // To create late reference for any late object not added to bundles
        _objectsToLateReference = referencedObjects.ToList();
    }
Example #27
0
    private static void BuildAssetBundles()
    {
        ClearAssetBundles();

        // You would probably want to parameterize this part
        Database.Instance.ReadFiles(AssetInfoXMLPath);

        // Validate asset infos
        ValidateAssetBundleAssetsInternal();

        // Get all asset infos and asset bundle infos from the database
        AssetInfo[]       assetInfos       = Database.Instance.GetEntries <AssetInfo>();
        AssetBundleInfo[] assetBundleInfos = Database.Instance.GetEntries <AssetBundleInfo>();

        // We need to build a list of all objects and object names (paths) for each
        // asset bundle.  Store these lists in two dictionaries, keyed to the
        // asset bundle info ID that each asset info references.
        Dictionary <ID, List <Object> > bundleObjects = new Dictionary <ID, List <Object> >();
        Dictionary <ID, List <string> > bundleNames   = new Dictionary <ID, List <string> >();

        foreach (AssetInfo info in assetInfos)
        {
            List <Object> objectList;
            if (!bundleObjects.TryGetValue(info.AssetBundleInfoRef.Entry.DatabaseID, out objectList))
            {
                objectList = new List <Object>();
                bundleObjects.Add(info.AssetBundleInfoRef.Entry.DatabaseID, objectList);
            }

            List <string> nameList;
            if (!bundleNames.TryGetValue(info.AssetBundleInfoRef.Entry.DatabaseID, out nameList))
            {
                nameList = new List <string>();
                bundleNames.Add(info.AssetBundleInfoRef.Entry.DatabaseID, nameList);
            }

            UnityEngine.Object asset = Resources.LoadAssetAtPath <UnityEngine.Object>(info.Path);
            if (asset == null)
            {
                throw new System.Exception("Invalid asset: " + info.Path);
            }

            objectList.Add(asset);
            nameList.Add(info.Path);
        }

        // Build bundles
        foreach (AssetBundleInfo info in assetBundleInfos)
        {
            // Get the list of objects for this bundle
            List <Object> objectList;
            if (!bundleObjects.TryGetValue(info.DatabaseID, out objectList))
            {
                Debug.LogWarning("No objects for bundle: " + info.Name);

                continue;
            }

            // Get the list of names for this bundle
            List <string> nameList;
            if (!bundleNames.TryGetValue(info.DatabaseID, out nameList))
            {
                throw new System.Exception("No names generated for objects");
            }

            // Build the bundle using the two lists
            string path = AssetBundlePath + "/" + info.Name + ".unity3d";
            BuildAssetBundleOptions options = (BuildAssetBundleOptions.CollectDependencies |
                                               BuildAssetBundleOptions.CompleteAssets |
                                               BuildAssetBundleOptions.DeterministicAssetBundle);
            BuildTarget target = BuildTarget.WebPlayer;
            if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(objectList.ToArray(),
                                                                  nameList.ToArray(),
                                                                  path,
                                                                  options,
                                                                  target))
            {
                throw new System.Exception("Unable to build asset bundle: " + info.Name);
            }

            AssetDatabase.SaveAssets();

            Debug.Log("Built bundle: " + info.Name);
        }
    }
Example #28
0
        private static bool BuildItemDataCollection(BuildAssetBundleData.ItemDataCollection itemDataCollection, BuildAssetBundleData.AssetBundleData assetBundleData)
        {
            List <Object> assetObjectList     = new List <Object>();
            List <string> assetObjectNameList = new List <string>();
            List <string> savePathList        = new List <string>();

            if (!itemDataCollection.GetBuildParams(assetBundleData, assetObjectList, assetObjectNameList, savePathList))
            {
                return(false);
            }

            if (assetObjectList.Count == 0)
            {
                return(true);
            }

            if (itemDataCollection.bind)
            {
                string dir  = null;
                string name = null;
                if (!SplitPath(itemDataCollection.savePath, out dir, out name))
                {
                    Debug.LogError("Error savePath:" + itemDataCollection.savePath);
                    return(false);
                }

                if (!Directory.Exists(URL.dataPath + "/" + assetBundleData.saveRoot + "/" + dir))
                {
                    try
                    {
                        Directory.CreateDirectory(URL.dataPath + "/" + assetBundleData.saveRoot + "/" + dir);
                    }
                    catch (System.Exception exception)
                    {
                        Debug.LogError("Error savePath:" + itemDataCollection.savePath + "->" + exception.Message);
                        return(false);
                    }
                }

                // isScene
                if (assetObjectList[0] == null)
                {
                    int numAssets = assetObjectList.Count;
                    for (int i = 0; i < numAssets; ++i)
                    {
                        assetObjectNameList[i] = URL.assets + "/" + assetObjectNameList[i];
                    }
                    if (!string.IsNullOrEmpty(BuildPipeline.BuildPlayer(assetObjectNameList.ToArray(), URL.assets + "/" + assetBundleData.saveRoot + "/" + itemDataCollection.savePath, assetBundleData.platform, BuildOptions.BuildAdditionalStreamedScenes)))
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(assetObjectList.ToArray(), assetObjectNameList.ToArray(), URL.assets + "/" + assetBundleData.saveRoot + "/" + itemDataCollection.savePath, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, assetBundleData.platform))
                    {
                        return(false);
                    }
                }
            }
            else
            {
                foreach (string savePath in savePathList)
                {
                    string dir  = null;
                    string name = null;
                    if (!SplitPath(savePath, out dir, out name))
                    {
                        Debug.LogError("Error savePath:" + savePath);
                        return(false);
                    }

                    if (!Directory.Exists(URL.dataPath + "/" + assetBundleData.saveRoot + "/" + dir))
                    {
                        try
                        {
                            Directory.CreateDirectory(URL.dataPath + "/" + assetBundleData.saveRoot + "/" + dir);
                        }
                        catch (System.Exception exception)
                        {
                            Debug.LogError("Error savePath:" + savePath + "->" + exception.Message);
                            return(false);
                        }
                    }
                }

                int length = assetObjectList.Count;
                // isScene
                if (assetObjectList[0] == null)
                {
                    string[] sceneNameList = new string[1];
                    for (int i = 0; i < length; ++i)
                    {
                        sceneNameList[0] = URL.assets + "/" + assetObjectNameList[i];
                        if (!string.IsNullOrEmpty(BuildPipeline.BuildPlayer(sceneNameList, URL.assets + "/" + assetBundleData.saveRoot + "/" + savePathList[i], assetBundleData.platform, BuildOptions.BuildAdditionalStreamedScenes)))
                        {
                            return(false);
                        }
                    }
                }
                else
                {
                    Object[] tempObjList  = new Object[1];
                    string[] tempNameList = new string[1];
                    for (int i = 0; i < length; ++i)
                    {
                        tempObjList[0]  = assetObjectList[i];
                        tempNameList[0] = assetObjectNameList[i];
                        if (!BuildPipeline.BuildAssetBundleExplicitAssetNames(tempObjList, tempNameList, URL.assets + "/" + assetBundleData.saveRoot + "/" + savePathList[i], BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, assetBundleData.platform))
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Example #29
0
    public static bool BuildStandardBundle(string id, string folder, string pathRoot, string filter, string prefix, bool recursive, bool shortNames, string parent, BundleOptions options)
    {
        string targetFolder = _outFolder;

        if (!Directory.Exists(targetFolder))
        {
            try
            {
                Directory.CreateDirectory(targetFolder);
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
                throw;
            }
        }

        List <Object> objectList = new List <Object>();
        List <string> nameList   = new List <string>();
        List <string> pathList   = new List <string>();

        string[] items = {};

        if (System.IO.File.Exists(folder))
        {
            items = new string[] { folder };
        }
        else if (System.IO.Directory.Exists(folder))
        {
            // Interrogate ALL found objects in the source path and all sub-directories
            items = Directory.GetFiles(folder, "*", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
        }

        string path = Path.Combine(_outFolder, string.Format("{0}.assetbundle", id));           //e.g. "/Users/User/perforce/ff7/main/Unity/android/download/audio.assetbundle"

        BuildAssetBundleOptions buildAssetBundleOptions = _bundleOptions | ((options & BundleOptions.Uncompressed) != 0 ? BuildAssetBundleOptions.UncompressedAssetBundle : 0);

        Debug.Log("Target - " + BuildSettings.Target + ", AssetBundleOptions - " + buildAssetBundleOptions);

        int bundleRelPathLength = folder.ToLower().IndexOf("bundles/");                 // e.g. folder: "Assets/Resources/Bundles/audio"

        if (bundleRelPathLength < 0)
        {
            bundleRelPathLength = 0;
        }

        // Let's see what we've got
        foreach (string s in items)
        {
            if (!string.IsNullOrEmpty(filter))
            {
                if (s.Contains(filter) == false)
                {
                    continue;                     // skip asset
                }
            }

            UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(s);
            if (obj != null && obj.GetType() == typeof(UnityEngine.Object))
            {
                var tmp = AssetDatabase.LoadAllAssetsAtPath(s);
                obj = null;
                for (int i = 0; i < tmp.Length; ++i)
                {
                    if (tmp[i] != null && tmp[i].GetType() != typeof(UnityEngine.Object) && !string.IsNullOrEmpty(tmp[i].name) && s.Contains(tmp[i].name))
                    {
                        Debug.Log("Loading " + s + " option type: " + (tmp[i] != null ? tmp[i].GetType().ToString() : "NULL OBJ"));
                    }
                }

                for (int i = 0; i < tmp.Length; ++i)
                {
                    if (tmp[i] != null && tmp[i].GetType() != typeof(UnityEngine.Object) && !string.IsNullOrEmpty(tmp[i].name) && s.Contains(tmp[i].name))
                    {
                        Debug.Log("Loaded " + s + " type: " + (tmp[i].GetType() != null ? tmp[i].GetType().ToString() : "NULL OBJ"));
                        obj = tmp[i];
                        break;
                    }
                }

                if (obj == null)
                {
                    Debug.Log("No asset loaded for " + s);
                }
            }
            else if (obj != null)
            {
                Debug.Log("Loaded " + s + " type: " + obj.GetType().ToString());
            }


            if (obj == null || (obj is MonoScript))
            {
                if (obj && obj is MonoScript)
                {
                    Debug.Log("SKIPPING MONOSCRIPT: " + s);
                }
                continue;
            }

            string p   = s.Substring(pathRoot.Length + 1);
            int    ext = p.LastIndexOf('.');
            if (ext > 0)
            {
                p = p.Substring(0, ext);
            }
            p = prefix + p.ToLower();

            if (shortNames)
            {
                p = Path.GetFileNameWithoutExtension(p);
            }

            nameList.Add(AssetName(p));
            pathList.Add(PathName(p));
            objectList.Add(obj);
        }

        if (objectList.Count == 0)
        {
            Debug.Log("Skipping empty bundle, id: " + id);
            return(false);
        }

        if ((options & BundleOptions.Force) != 0 || CheckDependancies(path, objectList.ToArray()))
        {
            // build
            bool result = BuildPipeline.BuildAssetBundleExplicitAssetNames(objectList.ToArray(), nameList.ToArray(), path, buildAssetBundleOptions, BuildSettings.Target);
            Debug.Log("BuildPipeline.BuildAssetBundleExplicitAssetNames : BundleID: " + id + " : " + (result ? "SUCCESSFUL " : "FAILED"));
        }

        // build the toc
        Hashtable toc = new Hashtable();
        FileInfo  fi  = new FileInfo(path);

        toc["paths"]  = pathList.ToArray();
        toc["parent"] = parent;
        toc["size"]   = fi.Length;
        toc["ts"]     = fi.LastWriteTime.Ticks;

#if UNITY_ANDROID
        toc["hash"] = CalculateFileHash(fi);
#endif

        _bundles[id] = toc;

        return(true);
    }
Example #30
0
        public static void PackBundle(List <PackRes_Def.BundleData> bundles,
                                      string dstPath,
                                      string platform,
                                      Dictionary <string, string> idxMap)
        {
            if (idxMap != null)
            {
                idxMap.Clear();
            }

            AssetDatabase.SaveAssets();

            Dictionary <string, string> checksumDict = new Dictionary <string, string>();

            foreach (PackRes_Def.BundleData bundle in bundles)
            {
                List <UnityEngine.Object> objs  = new List <UnityEngine.Object>();
                List <string>             names = new List <string>();

                if (bundle.srcFiles.Length <= 0)
                {
                    continue;
                }

                checksumDict.Clear();
                for (int i = 0; i < bundle.srcFiles.Length; ++i)
                {
                    string             file = bundle.srcFiles[i];
                    string             name = bundle.names[i];
                    UnityEngine.Object obj  = CreateAsset(file.Trim(PackRes_Def.trim));
                    objs.Add(obj);
                    names.Add(name);

                    if (idxMap != null)
                    {
                        if (idxMap.ContainsKey(name))
                        {
                            throw new PackRes_Def.PckException("duplicate file name: " + name);
                        }
                        idxMap.Add(name, bundle.bundleFile);
                    }
                    AddFileChecksum(checksumDict, file);
                }

                BuildAssetBundleOptions option = GetBuildOption(bundle.option);
                string      dp      = GetOrCreateAbsPath(dstPath);
                string      dstFile = Path.Combine(dp, bundle.bundleFile.Trim(PackRes_Def.trim));
                BuildTarget pm      = GetBuildTarget(platform);

                if (!bundle.compress)
                {
                    option |= BuildAssetBundleOptions.UncompressedAssetBundle;
                }

                string dictPath = dstFile + ".hash";
                Dictionary <string, string> existDict = LoadDict(dictPath);
                if (File.Exists(dstFile) && SameDict(existDict, checksumDict))
                {
                    //Logger.LogMsg("use exist " + dstFile);
                    continue;
                }

                BuildPipeline.BuildAssetBundleExplicitAssetNames(objs.ToArray(),
                                                                 names.ToArray(),
                                                                 dstFile,
                                                                 option, pm);

                Debug.Log("checksumDict.length " + checksumDict.Count);
                SaveDict(dictPath, checksumDict);
            }
        }