Пример #1
0
        private static bool CreatABPacker(BuildTarget platform)
        {
            List <string> updateFileList   = new List <string>();
            List <string> updateScriptList = new List <string>();

            Dictionary <string, string>         lastVersionMd5List          = ABHelper.ReadMd5File(PlatformABExportPath + "/" + (CurVersionNum - 1) + "/" + ABHelper.Md5FileName);
            Dictionary <string, List <string> > lastVersionDependenciesList = ABHelper.ReadDependFile(PlatformABExportPath + "/" + (CurVersionNum - 1) + "/" + ABHelper.DependFileName);

            foreach (KeyValuePair <string, List <string> > pair in CurVersionDependenciesList)
            {
                string pathName = pair.Key;
                if (!lastVersionDependenciesList.ContainsKey(pathName.ToLower()))
                {
                    if (IsScriptFileRes(pathName))
                    {
                        updateScriptList.Add(pathName);
                    }
                    else
                    {
                        updateFileList.Add(pathName);
                    }
                    continue;
                }
                foreach (string depend in pair.Value)
                {
                    if (!lastVersionDependenciesList[pathName.ToLower()].Contains(depend.ToLower()))
                    {
                        if (IsScriptFileRes(pathName))
                        {
                            updateScriptList.Add(pathName);
                        }
                        else
                        {
                            updateFileList.Add(pathName);
                        }
                        break;
                    }
                    else if (CurVersionMd5List[depend].ToLower() != lastVersionMd5List[depend.ToLower()])
                    {
                        if (IsScriptFileRes(pathName))
                        {
                            updateScriptList.Add(pathName);
                        }
                        else
                        {
                            updateFileList.Add(pathName);
                        }
                        break;
                    }
                }
            }

            // 检测cs和dll脚本
            if (updateScriptList.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var pair in updateScriptList)
                {
                    sb.AppendLine(pair);
                }
                if (EditorUtility.DisplayDialog("提示", "检测到有cs等脚本的更新!!\n “停止”则中断打包,“忽略”则继续。如下:\n" + sb, "停止", "忽略"))
                {
                    throw new Exception("打包中断!!!!!!!!!!");
                }
            }

            if (updateFileList.Count > 0)
            {
                ClearAssetBundlesName();
                AssetDatabase.Refresh();

                foreach (string path in updateFileList)
                {
                    string fileName;
                    switch (CurVersionFileType[path])
                    {
                    case "0":
                        foreach (string path2 in CurVersionDependenciesList[path])
                        {
                            fileName = (ABHelper.GetFileFolderPath(path2).Replace(ResFolder, "")) + ".ab";
                            fileName = CreatFileUrlMd5(fileName);
                            AssetImporter.GetAtPath(path2).assetBundleName = fileName;
                        }
                        break;

                    case "1":
                        CopyLuaFiles(path);
                        break;

                    case "2":
                        fileName = (ABHelper.GetFileFullPathWithoutFtype(path).Replace(ResFolder, "")) + ".ab";
                        fileName = CreatFileUrlMd5(fileName);
                        AssetImporter.GetAtPath(path).assetBundleName = fileName;
                        break;

                    case "3":
                        fileName = (ABHelper.GetFileFullPathWithoutFtype(path).Replace(ResFolder, "")) + ".ab";
                        fileName = CreatFileUrlMd5(fileName);
                        AssetImporter.GetAtPath(path).assetBundleName = fileName;
                        break;

                    default: break;
                    }
                }
                try
                {
                    // 生成ab文件
                    BuildPipeline.BuildAssetBundles(CurVersionABExportPath, BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.DeterministicAssetBundle, platform);
                }
                catch (Exception e)
                {
                    BuildFailure();
                    Debug.LogError("打包异常!!" + e.Message);
                }
                System.Threading.Thread.Sleep(1000);

                ClearAssetBundlesName();
                AssetDatabase.Refresh();
            }
            else
            {
                BuildFailure();
            }

            bool result = updateFileList.Count > 0;

            if (result)
            {
                // 删除不用的manifest
                List <string> allFiles = ABHelper.GetAllFilesPathInDir(PlatformABExportPath);
                foreach (string path in allFiles)
                {
                    if (path.EndsWith(".manifest"))
                    {
                        File.Delete(path);
                    }
                    if (path.EndsWith(CurVersionNum.ToString()))
                    {
                        File.Delete(path);
                    }
                }
            }
            return(result);
        }
Пример #2
0
    ////[MenuItem("LuaFramework/Build Android Resource", false, 101)]
    //public static void BuildAndroidResource() {
    //    BuildAssetResource(BuildTarget.Android);
    //}

    ////[MenuItem("LuaFramework/Build Windows Resource", false, 102)]
    //public static void BuildWindowsResource() {
    //    BuildAssetResource(BuildTarget.StandaloneWindows);
    //}

    /// <summary>
    /// 生成绑定素材
    /// </summary>
    public static void BuildAssetResource(BuildTarget target)
    {
        string outPath = "Assets/" + AppConst.AssetDir;

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

        if (Directory.Exists(Util.DataPath))
        {
            Directory.Delete(Util.DataPath, true);
        }
        Directory.CreateDirectory(outPath);
        AssetDatabase.Refresh();

        LuaMaps.Clear();
        ResDic.Clear();
        if (AppConst.LuaBundleMode)
        {
            HandleLuaBundle();
        }
        else
        {
            //HandleLuaFile();
        }
        if (AppConst.ExampleMode)
        {
            //HandleExampleBundle();
        }
        List <string> resList = GetAllResDirs(AppConst.ResPath);

        if (resList.Count > 0 && resList != null)
        {
            for (int i = 0; i < resList.Count; i++)
            {
                Debug.Log("文件目录===" + resList[i]);
                SetAssetBundleName(resList[i]);
            }
        }
        Debug.Log("开始打包了");

        BuildPipeline.BuildAssetBundles(outPath, LuaMaps.ToArray(), BuildAssetBundleOptions.None, target);
        BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.None, target);

        Debug.Log("打出ab资源了,开始去打包场景");

        BuildScene(outPath, target);
        BuildFileIndex();

        Debug.Log("场景打包完毕,开始去生成xml");

        //分析依赖
        foreach (var info in ResDic)
        {
            string[] str = AssetDatabase.GetAssetBundleDependencies(info.Value.bundleName, true);
            foreach (var s in str)
            {
                info.Value.deps.Add(s);
            }
        }
        //生成XML
        XmlDocument doc  = new XmlDocument();
        XmlElement  root = doc.CreateElement("bundles");

        foreach (var info in ResDic)
        {
            XmlElement item       = doc.CreateElement("bundle");
            XmlElement bundleName = doc.CreateElement("bundleName");
            bundleName.InnerText = info.Value.bundleName;
            item.AppendChild(bundleName);
            foreach (string s in info.Value.assetName)
            {
                XmlElement AssetName = doc.CreateElement("assetName");
                AssetName.InnerText = s;
                item.AppendChild(AssetName);
            }
            foreach (string s in info.Value.deps)
            {
                XmlElement deps = doc.CreateElement("deps");
                deps.InnerText = s;
                item.AppendChild(deps);
            }
            root.AppendChild(item);
        }
        doc.AppendChild(root);
        doc.Save(outPath + "/" + AppConst.MoonXml);
        UnityEngine.Debug.Log("xml生成完毕");

        //BuildPipeline
        AssetDatabase.Refresh();
    }
Пример #3
0
        public static void BuildAssetBundle(AssetBundleSetting assetBundleSetting)
        {
            Dictionary <string, AssetBundleData>     assetBundleDataDict     = new Dictionary <string, AssetBundleData>();
            Dictionary <string, AssetBundleRuleType> assetBundleRuleTypeDict = new Dictionary <string, AssetBundleRuleType>();
            string path = DirectoryUtil.GetDirectoryPath($"{assetBundleSetting.outputPath}/{GetPlatformForAssetBundle(EditorUserBuildSettings.activeBuildTarget)}");

            foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List <DirectoryInfo>()))
            {
                item.Delete();
            }
            foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List <FileInfo>()))
            {
                item.Delete();
            }
            List <AssetBundleBuild> assetBundleBuildList = new List <AssetBundleBuild>();

            foreach (AssetBundleRule item in assetBundleSetting.assetBundleRuleList)
            {
                if (item.assetBundleRuleType == AssetBundleRuleType.File)
                {
                    FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List <FileInfo>());
                    if (fileInfos.Length == 0)
                    {
                        continue;
                    }
                    List <FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
                    foreach (FileInfo fileInfo in fileInfoList)
                    {
                        assetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("Assets")).Replace("\\", "/"), AssetBundleRuleType.File);
                    }
                }
                if (item.assetBundleRuleType == AssetBundleRuleType.Directory)
                {
                    DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List <DirectoryInfo>()
                    {
                        new DirectoryInfo(item.path)
                    });
                    if (directoryInfos.Length == 0)
                    {
                        continue;
                    }
                    foreach (DirectoryInfo directoryInfo in directoryInfos)
                    {
                        foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                        {
                            assetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("Assets")).Replace("\\", "/"), AssetBundleRuleType.Directory);
                        }
                    }
                }
            }
            foreach (AssetBundleData item in assetBundleSetting.assetBundleDataList)
            {
                assetBundleBuildList.Add(new AssetBundleBuild()
                {
                    assetBundleName = item.assetBundleName,
                    assetNames      = item.assetNames,
                });
            }
            AssetBundleManifest assetBundleManifest = BuildPipeline.BuildAssetBundles(path, assetBundleBuildList.ToArray(), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);

            foreach (AssetBundleData item in assetBundleSetting.assetBundleDataList)
            {
                item.assetBundleHash = assetBundleManifest.GetAssetBundleHash(item.assetBundleName).ToString();
                BuildPipeline.GetCRCForAssetBundle($"{path}/{item.assetBundleName}", out item.assetBundleCRC);
                assetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.assetBundleName), item);
            }
            AssetBundleConfig assetBundleConfig = new AssetBundleConfig(assetBundleSetting.buildId, assetBundleDataDict, assetBundleRuleTypeDict);

            FileUtil.SaveAsset(path, "AssetBundleConfig.json", JsonUtil.ToJson(assetBundleConfig));
            AssetDatabase.Refresh();
        }
Пример #4
0
 static void BuildAllAssetBundles()
 {
     BuildPipeline.BuildAssetBundles($"{Application.streamingAssetsPath}/AssetBundles", BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.Android);
 }
Пример #5
0
        private void BuildAllAssetBundles()
        {
            assetBundleBuilds = new List <AssetBundleBuild>();
            string        assetBundleDirectory = "Assets/AssetBundles";
            string        msgEnd = "";
            DirectoryInfo dir    = new DirectoryInfo(assetBundleDirectory);

            if (!Directory.Exists(assetBundleDirectory))
            {
                Directory.CreateDirectory(assetBundleDirectory);
            }

            foreach (string bundle in bundleNames)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    if ((file.Extension != ".assets" && file.Extension != ".maps") || exportBundle[bundle])
                    {
                        file.Delete();
                    }
                }
                if (exportBundle[bundle])
                {
                    AssetBundleBuild build = new AssetBundleBuild
                    {
                        assetBundleName    = bundle,
                        assetBundleVariant = AssetImporter.GetAtPath(assetBundleDirectory).assetBundleVariant,
                        assetNames         = AssetDatabase.GetAssetPathsFromAssetBundle(bundle)
                    };
                    assetBundleBuilds.Add(build);
                }
                try
                {
                    EditorPrefs.SetBool("ExportBundle" + bundle, exportBundle[bundle]);
                }
                catch (Exception)
                {
                    EditorPrefs.SetBool("ExportBundle" + bundle, true);
                }
            }

            BuildPipeline.BuildAssetBundles(assetBundleDirectory, assetBundleBuilds.ToArray(), buildAssetBundleOptions, BuildTarget.StandaloneWindows);

            bundleNames = new List <string>(AssetDatabase.GetAllAssetBundleNames());

            foreach (FileInfo file in dir.GetFiles("*.*"))
            {
                if (bundleNames.Contains(file.Name))
                {
                    string ext = ".assets";
                    foreach (string asset in AssetDatabase.GetAssetPathsFromAssetBundle(file.Name))
                    {
                        Type assetType = AssetDatabase.GetMainAssetTypeAtPath(asset);
                        if (assetType == typeof(SceneAsset))
                        {
                            ext = ".maps";
                            break;
                        }
                        else if (assetType.FullName == "UMA.RaceData" || assetType.FullName == "UMA.SlotDataAsset" || assetType.FullName == "UMA.OverlayDataAsset")
                        {
                            ext = ".uma";
                            break;
                        }
                    }
                    file.MoveTo(file.FullName + ext);

                    if (modExportDirectories[Path.GetFileNameWithoutExtension(file.Name)].Length > "C:/".Length)
                    {
                        if (exportToModFolders && modExportDirectories.ContainsKey(file.Name.Substring(0, file.Name.Length - ext.Length)))
                        {
                            file.CopyTo(modExportDirectories[Path.GetFileNameWithoutExtension(file.Name)] + "/" + file.Name, true);
                            msgEnd = " and copied into mod folders";
                        }
                    }
                    else
                    {
                        Debug.LogWarning("Could not fetch directory for assetbundle " + file.Name);
                        msgEnd = ". Could not copy to mod folders";
                    }
                }
                else if (file.Extension != ".assets" && file.Extension != ".maps" && file.Extension != ".uma")
                {
                    file.Delete();
                }
                //Debug.Log(file.Name.Substring(0, file.Name.Length - 7));
            }

            AssetDatabase.Refresh();
            if (assetBundleBuilds.ToArray().Length > 0)
            {
                string bundleNames = "";
                string s           = "";
                foreach (AssetBundleBuild build in assetBundleBuilds)
                {
                    if (assetBundleBuilds[0].assetBundleName == build.assetBundleName)
                    {
                        bundleNames = " " + build.assetBundleName;
                    }
                    else if (assetBundleBuilds[assetBundleBuilds.Count - 1].assetBundleName == build.assetBundleName)
                    {
                        s           = "s";
                        bundleNames = bundleNames + " and " + build.assetBundleName;
                    }
                    else
                    {
                        s           = "s";
                        bundleNames = bundleNames + ", " + build.assetBundleName;
                    }
                }
                Debug.Log("Created Asset Bundle" + s + bundleNames /*+ " in " + dir.FullName*/ + msgEnd);
            }
        }
Пример #6
0
 public static void Build()
 {
     //将资源打包到StreamingAssets文件夹下
     BuildPipeline.BuildAssetBundles(Application.dataPath + @"\AssetBundle", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
 }
Пример #7
0
 static void PerformAssetBundleBuild()
 {
     BuildPipeline.BuildAssetBundles("../AssetBundles/", BuildAssetBundleOptions.ChunkBasedCompression,
                                     BuildTarget.StandaloneLinux64);
 }
Пример #8
0
 static void BuildAllAssetBundles()
 {
     BuildPipeline.BuildAssetBundles(@"C:\Users\Chloee\Documents\AT_OpenWorld\OpenWorldAT\AssetBundles", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.StandaloneWindows64);
 }
Пример #9
0
 static void BuildAllAssetBundles()
 {
     BuildPipeline.BuildAssetBundles("Assets/ABs", BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android);
 }
Пример #10
0
    static void CreateAnAssetBundle()
    {
        // Clean all loaded assetbundles
#if UNITY_2017_1_OR_NEWER
        Caching.ClearCache();
#else
        Caching.CleanCache();
#endif

        var currentSelect = Selection.activeObject;
        if (currentSelect == null)
        {
            Debug.Log("Without any selection");
            return;
        }

        string folderName = currentSelect.name;
        Debug.Log("folderName = " + folderName);

        var folderPath = AssetDatabase.GetAssetPath(currentSelect.GetInstanceID());
        Debug.Log("folderPath = " + folderPath);
        if (!Directory.Exists(folderPath))
        {
            Debug.Log("Must be root of controller model");
            return;
        }

        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

        var assetBundleBuilds = new List <AssetBundleBuild>();

        foreach (Object obj in SelectedAsset)
        {
            string sourcePath = AssetDatabase.GetAssetPath(obj);

            assetBundleBuilds.Add(new AssetBundleBuild()
            {
                assetBundleName    = obj.name,
                assetBundleVariant = "",
                assetNames         = new string[] {
                    sourcePath
                }
            });
        }

        var path = Path.GetFullPath(Application.dataPath + "/../Unity");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        else
        {
            DirectoryInfo di = new DirectoryInfo(path);
            foreach (FileInfo fi in di.GetFiles())
            {
                fi.Delete();
            }
        }

        BuildPipeline.BuildAssetBundles(
            path,
            assetBundleBuilds.ToArray(),
            BuildAssetBundleOptions.ForceRebuildAssetBundle,
            BuildTarget.Android);

        AssetDatabase.Refresh();
    }
Пример #11
0
 //导出
 static void Export()
 {
     BuildPipeline.BuildAssetBundles("bundles"); //bundels在asset路径上创建一个文件夹保存导出的东西
 }
 public static void Export()
 {
     BuildPipeline.BuildAssetBundles(EditorUtility.OpenFolderPanel("Bundles Path", "", ""), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
 }
Пример #13
0
        public override void Build(BuildTarget target,
                                   Model.NodeData node,
                                   IEnumerable <PerformGraph.AssetGroups> incoming,
                                   IEnumerable <Model.ConnectionData> connectionsToOutput,
                                   PerformGraph.Output Output,
                                   Action <Model.NodeData, string, float> progressFunc)
        {
            if (incoming == null)
            {
                return;
            }

            var aggregatedGroups = new Dictionary <string, List <AssetReference> >();

            aggregatedGroups[key] = new List <AssetReference>();

            if (progressFunc != null)
            {
                progressFunc(node, "Collecting all inputs...", 0f);
            }

            foreach (var ag in incoming)
            {
                foreach (var name in ag.assetGroups.Keys)
                {
                    if (!aggregatedGroups.ContainsKey(name))
                    {
                        aggregatedGroups[name] = new List <AssetReference>();
                    }
                    aggregatedGroups[name].AddRange(ag.assetGroups[name].AsEnumerable());
                }
            }

            var bundleOutputDir = PrepareOutputDirectory(target, node, true, true);
            var bundleNames     = aggregatedGroups.Keys.ToList();
            var bundleVariants  = new Dictionary <string, List <string> >();

            if (progressFunc != null)
            {
                progressFunc(node, "Building bundle variants map...", 0.2f);
            }

            // get all variant name for bundles
            foreach (var name in aggregatedGroups.Keys)
            {
                if (!bundleVariants.ContainsKey(name))
                {
                    bundleVariants[name] = new List <string>();
                }
                var assets = aggregatedGroups[name];
                foreach (var a in assets)
                {
                    var variantName = a.variantName;
                    if (!bundleVariants[name].Contains(variantName))
                    {
                        bundleVariants[name].Add(variantName);
                    }
                }
            }

            int validNames = 0;

            foreach (var name in bundleNames)
            {
                var assets = aggregatedGroups[name];
                // we do not build bundle without any asset
                if (assets.Count > 0)
                {
                    validNames += bundleVariants[name].Count;
                }
            }

            AssetBundleBuild[]          bundleBuild     = new AssetBundleBuild[validNames];
            List <AssetImporterSetting> importerSetting = null;

            if (!m_overwriteImporterSetting)
            {
                importerSetting = new List <AssetImporterSetting> ();
            }

            int bbIndex = 0;

            foreach (var name in bundleNames)
            {
                foreach (var v in bundleVariants[name])
                {
                    var assets = aggregatedGroups[name];

                    if (assets.Count <= 0)
                    {
                        continue;
                    }

                    bundleBuild[bbIndex].assetBundleName    = name;
                    bundleBuild[bbIndex].assetBundleVariant = v;
                    bundleBuild[bbIndex].assetNames         = assets.Where(x => x.variantName == v).Select(x => x.importFrom).ToArray();

                    /**
                     * WORKAROND: This will be unnecessary in future version
                     * Unity currently have issue in configuring variant assets using AssetBundleBuild[] that
                     * internal identifier does not match properly unless you configure value in AssetImporter.
                     */
                    if (!string.IsNullOrEmpty(v))
                    {
                        foreach (var path in bundleBuild[bbIndex].assetNames)
                        {
                            AssetImporter importer = AssetImporter.GetAtPath(path);

                            if (importer.assetBundleName != name || importer.assetBundleVariant != v)
                            {
                                if (!m_overwriteImporterSetting)
                                {
                                    importerSetting.Add(new AssetImporterSetting(importer));
                                }
                                importer.SetAssetBundleNameAndVariant(name, v);
                                importer.SaveAndReimport();
                            }
                        }
                    }

                    ++bbIndex;
                }
            }

            if (progressFunc != null)
            {
                progressFunc(node, "Building Asset Bundles...", 0.7f);
            }

            AssetBundleManifest m = BuildPipeline.BuildAssetBundles(bundleOutputDir, bundleBuild, (BuildAssetBundleOptions)m_enabledBundleOptions[target], target);

            var output = new Dictionary <string, List <AssetReference> >();

            output[key] = new List <AssetReference>();

            var generatedFiles = FileUtility.GetAllFilePathsInFolder(bundleOutputDir);
            var manifestName   = GetManifestName(target);

            // add manifest file
            bundleVariants.Add(manifestName.ToLower(), new List <string> {
                null
            });
            foreach (var path in generatedFiles)
            {
                var fileName = path.Substring(bundleOutputDir.Length + 1);
                if (IsFileIntendedItem(fileName, bundleVariants))
                {
                    if (fileName == manifestName)
                    {
                        output[key].Add(AssetReferenceDatabase.GetAssetBundleManifestReference(path));
                    }
                    else
                    {
                        output[key].Add(AssetReferenceDatabase.GetAssetBundleReference(path));
                    }
                }
            }

            if (Output != null)
            {
                var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
                          null : connectionsToOutput.First();
                Output(dst, output);
            }

            if (importerSetting != null)
            {
                importerSetting.ForEach(i => i.WriteBack());
            }

            AssetBundleBuildReport.AddBuildReport(new AssetBundleBuildReport(node, m, manifestName, bundleBuild, output[key], aggregatedGroups, bundleVariants));
        }
Пример #14
0
		public override void OnInspectorGUI()
		{
			DrawDefaultInspector ();

			var projectImport = (ProjectImport)target;

			GUILayout.Space (8);

			EditorGUILayout.BeginVertical (EditorStyles.helpBox);
			foreach (var resource in projectImport.Explorer.Resources)
			{
				EditorGUILayout.LabelField (resource.Name);
			}

			if (Spritesheet != null)
			{
				var rect = GUILayoutUtility.GetRect (0, 250);
				var centerRect = new Rect (rect.center.x - (rect.height * 0.5f), rect.y, rect.height, rect.height);
				GUI.DrawTexture (centerRect, Spritesheet);
			}

			if (GUILayout.Button ("Reload"))
			{
				projectImport.Reload ();
			}

			if (GUILayout.Button ("Create"))
			{
				string path = AssetDatabase.GetAssetPath (target);
				path = path.Substring (0, path.LastIndexOf ('/'));
				Debug.Log (path);

				/*foreach (var resource in projectImport.Explorer.Resources)
				{
					string assetFolder = path + "/" + resource.Name;
					if (!AssetDatabase.IsValidFolder (assetFolder))
					{
						assetFolder = AssetDatabase.CreateFolder (path, resource.Name);
						assetFolder = AssetDatabase.GUIDToAssetPath (assetFolder);
					}

					string assetImportPath = assetFolder + "/" + resource.Name + ".asset";

					var assetImport = AssetDatabase.LoadAssetAtPath<AssetImport> (assetImportPath);
					if (assetImport == null)
					{
						assetImport = CreateInstance<AssetImport> ();
						AssetDatabase.CreateAsset (assetImport, assetImportPath);
					}
					
					AssetImporter.GetAtPath (assetImportPath).SetAssetBundleNameAndVariant (target.name, "");

					var assetIcon = resource.FindIcon().LoadImage ();

					AssetDatabase.AddObjectToAsset (assetIcon, assetImport);
					AssetDatabase.ImportAsset (AssetDatabase.GetAssetPath (assetIcon));

				} */
			}

			if (GUILayout.Button ("Export"))
			{
				string path = AssetDatabase.GetAssetPath (target);
				path = path.Substring (0, path.LastIndexOf ('/'));
				string exportDirectory = path + "/" + target.name + DateTime.Now.ToString ("ddmmyy");
				if (!Directory.Exists (exportDirectory))
				{
					Directory.CreateDirectory (exportDirectory);
				}
				Debug.Log (exportDirectory);

				var manifest = BuildPipeline.BuildAssetBundles (exportDirectory, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
			}
		}
Пример #15
0
 static void buildAsset()
 {
     BuildPipeline.BuildAssetBundles("Assets/Bundle", BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);
 }
Пример #16
0
        void OnGUI()
        {
            if (PlayerPrefs.HasKey("TargetPlatform"))
            {
                runtimePlatform = (BuildTarget)PlayerPrefs.GetInt("TargetPlatform");
            }

            EditorGUILayout.HelpBox("The tool will build all assets serialized into Assetbundles separately. ", MessageType.None);

            EditorGUILayout.HelpBox("[Important]!!! Select target platform you want to build assets! ", MessageType.Error);
            runtimePlatform = (BuildTarget)EditorGUILayout.EnumPopup("Target Platform", runtimePlatform);
            PlayerPrefs.SetInt("TargetPlatform", (int)runtimePlatform);
            //if(GUILayout.Button(""))
            //AssetDatabase.GetAssetPathsFromAssetBundle
            EditorGUILayout.HelpBox("Click 1,2,3 in order to build assets!", MessageType.Info);

            EditorGUILayout.HelpBox("AssetBundle Settings ", MessageType.None);

            EditorGUILayout.HelpBox(string.Format("Scene Data Count: {0} Maps:{1}", AllSceneData.Count.ToString(), SceneDataNames), MessageType.None);


            if (GUILayout.Button("1-Reload  Cooked Scene Data "))
            {
                LoadSceneData();
            }
            if (GUILayout.Button("2-Label Assets"))
            {
                List <GameObject> AllCurrentAssets = new List <GameObject>();

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

                foreach (SceneData sceneData in AllSceneData)
                {
                    foreach (GameObject sceneDataObjects in sceneData.SceneObjectReferences)
                    {
                        AllCurrentAssets.Add(sceneDataObjects);
                    }
                }
                foreach (GameObject CurrentAsset in AllCurrentAssets)
                {
                    string Path = AssetDatabase.GetAssetPath(CurrentAsset);

                    AssetImporter assetImporter = AssetImporter.GetAtPath(Path);

                    string AssetPathToGUID = AssetNameCorretor(AssetDatabase.AssetPathToGUID(Path));

                    AllCurrentAssetGUID.Add(AssetPathToGUID);

                    if (PlayerPrefs.GetString(AssetPathToGUID) == assetImporter.assetTimeStamp.ToString())
                    {
                        Debug.Log("Pass");
                        continue;
                    }

                    PlayerPrefs.SetString(AssetPathToGUID, assetImporter.assetTimeStamp.ToString());

                    GameObject Prefab = Instantiate(CurrentAsset);

                    #region  务器打包文件
                    GameObject ClientAsset = PrefabUtility.CreatePrefab("Assets/res/Cooked/" + CurrentAsset.name + ".prefab", Prefab);
                    assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ClientAsset));
                    if (assetImporter.assetBundleName != AssetPathToGUID)
                    {
                        assetImporter.SetAssetBundleNameAndVariant(AssetPathToGUID, "clientsceneobject");
                    }

                    #endregion

                    #region  务器资源处理


                    foreach (MeshRenderer meshRenderer in Prefab.GetComponentsInChildren <MeshRenderer>())
                    {
                        DestroyImmediate(meshRenderer);
                    }
                    foreach (MeshFilter mesh in Prefab.GetComponentsInChildren <MeshFilter>())
                    {
                        DestroyImmediate(mesh);
                    }


                    #region  务器打包文件
                    GameObject DelicateAsset = PrefabUtility.CreatePrefab("Assets/res/Cooked/DelicatedServer/" + CurrentAsset.name + ".prefab", Prefab);
                    assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(DelicateAsset));
                    if (assetImporter.assetBundleName != AssetPathToGUID)
                    {
                        assetImporter.SetAssetBundleNameAndVariant(AssetPathToGUID, "mastersceneobject");
                    }
                    #endregion

                    DestroyImmediate(Prefab);
                    #endregion
                }
                string[] AssetBundleNames = AssetDatabase.GetAllAssetBundleNames();

                foreach (string AssetBundleName in AssetBundleNames)
                {
                    string[] AllAssetBundlePaths = AssetDatabase.GetAssetPathsFromAssetBundle(AssetBundleName);
                    foreach (string AssetBundlePath in AllAssetBundlePaths)
                    {
                        GameObject PreviousAsset = AssetDatabase.LoadAssetAtPath(AssetBundlePath, typeof(GameObject)) as GameObject;

                        AssetImporter assetImporter = AssetImporter.GetAtPath(AssetBundlePath);

                        string AssetPathToGUID = assetImporter.assetBundleName;

                        if (!AllCurrentAssetGUID.Contains(AssetPathToGUID))
                        {
                            if (!assetImporter.assetBundleVariant.Contains("sceneobject"))
                            {
                                continue;
                            }
                            Debug.Log(AssetBundlePath);
                            assetImporter.assetBundleName = null;
                            //assetImporter.assetBundleVariant = null;
                            assetImporter.SaveAndReimport();
                        }
                    }
                }
            }
            if (runtimePlatform != BuildTarget.NoTarget)
            {
                if (GUILayout.Button("3-Build Sub-Assets"))
                {
                    if (!EditorUtility.DisplayDialog("[Important]Comfirm", "Compile Asset on Target Platform:" + runtimePlatform.ToString(), "Yes", "No"))
                    {
                        return;
                    }

                    DirectoryInfo folder = new DirectoryInfo("Assets/res/Cooked/.packages/");
                    if (!folder.Exists)
                    {
                        folder.Create();
                    }

                    AssetBundleManifest assetbundleMainifest = BuildPipeline.BuildAssetBundles("Assets/res/Cooked/.packages", BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.DeterministicAssetBundle, runtimePlatform);
                    Hashtable           Info = new Hashtable();
                    foreach (FileInfo file in folder.GetFiles("*.extramesh"))
                    {
                        List <string> Details = new List <string>();
                        Details.Add(GetMD5HashFromFile(file.FullName));
                        Info.Add(file.Name, Details);
                    }

                    StreamWriter streamWriter = new StreamWriter(folder + "md5.checker");
                    streamWriter.Write(EditorJsonUtility.ToJson(Info));
                    streamWriter.Close();

                    if (!EditorUtility.DisplayDialog("Copy", "Copy cooked assets to Streamassets Folder", "Yes", "No"))
                    {
                        return;
                    }
                    DirectoryInfo dir        = new DirectoryInfo("Assets/res/Cooked/.packages/");
                    string        path       = "Assets/res/Cooked/.packages/";
                    string        Seach_Path = Application.streamingAssetsPath + "/TWRPackages";

                    DirectoryInfo TargetDir = new DirectoryInfo(Application.streamingAssetsPath + "/TWRPackages");
                    if (!TargetDir.Exists)
                    {
                        TargetDir.Create();
                    }

                    AssetDatabase.RemoveUnusedAssetBundleNames();

                    string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();

                    for (int i = 0; i < allAssetBundleNames.Length; i++)
                    {
#if ClientCode
                        if (allAssetBundleNames[i].Contains("master"))
                        {
                            continue;
                        }
#else
                        if (allAssetBundleNames[i].Contains("client"))
                        {
                            continue;
                        }
#endif

                        string source = path + "/" + allAssetBundleNames[i];

                        string target = Seach_Path + "/" + allAssetBundleNames[i];

                        if (!File.Exists(target) || (GetMD5HashFromFile(target) != GetMD5HashFromFile(source)))
                        {
                            File.Copy(source, target, true);
                        }
                    }

                    File.Copy(path + "/.packages", Seach_Path + "/main.packages", true);
                }
            }
        }
    public static void BuildAssetBundle()
    {
        //设置各个资源的所属的AB包名之后

        //找到所有的AssetBundle
        string[] allAbName = AssetDatabase.GetAllAssetBundleNames();
        //所有的资源,key是资源的全路径 value是AB包名
        Dictionary <string, string> assetPathDic = new Dictionary <string, string>();

        for (int i = 0; i < allAbName.Length; i++)
        {
            //获取这个AB包含的资源
            string[] dependAssetArr = AssetDatabase.GetAssetPathsFromAssetBundle(allAbName[i]);
            for (int j = 0; j < dependAssetArr.Length; j++)
            {
                if (!dependAssetArr[j].EndsWith(".cs"))
                {
                    assetPathDic.Add(dependAssetArr[j], allAbName[i]);
                }
                EditorUtility.DisplayProgressBar("AB下的资源", "资源" + dependAssetArr[j], j + 1 / dependAssetArr.Length);
            }
        }
        //增量删除多余的AB包
        IncrementalDeleteAB();
        //生成自己的配置表
        AssetBundleConfig config = CreateConfig(assetPathDic);

        //序列成XML
        string xmlPath = Application.dataPath + "/AssetBundleConfig.xml";

        if (File.Exists(xmlPath))
        {
            File.Delete(xmlPath);
        }
        FileStream    fs = new FileStream(xmlPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
        StreamWriter  sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
        XmlSerializer xs = new XmlSerializer(typeof(AssetBundleConfig));

        xs.Serialize(sw, config);
        sw.Close();
        fs.Close();



        //序列化成二进制文件
        FileStream fs1 = new FileStream(m_ABConfigBytePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

        fs1.Seek(0, SeekOrigin.Begin);
        fs1.SetLength(0);
        BinaryFormatter bf = new BinaryFormatter();

        bf.Serialize(fs1, config);
        fs1.Close();
        //刷新上一步后的资源目录
        AssetDatabase.Refresh();
        SetABName("assetbundleconfig", m_ABConfigBytePath);

        if (!Directory.Exists(m_BuildABPath))
        {
            Directory.CreateDirectory(m_BuildABPath);
        }

        //打包
        AssetBundleManifest mainfest = BuildPipeline.BuildAssetBundles(m_BuildABPath, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);

        if (mainfest == null)
        {
            Debug.LogError("打包失败");
        }
        else
        {
            Debug.Log("打包完成");
        }

        DeleteBuildPathMainfest();

        //加密AB包
        EncryptAssetBundle();
    }
 static void BuildBundlesIOS()
 {
     BuildPipeline.BuildAssetBundles("AssetsBundles", BuildAssetBundleOptions.None, BuildTarget.iOS);
 }
Пример #19
0
        static void BuildBundles(BuildTarget targetPlatform, string[] files)
        {
            var buildInfos = new Dictionary <string, AssetBundleBuild>();

            var filters = new List <ResAbstractBuildFilter>()
            {
                new ResPrefabBuildFilter(),
                new ResLuaBuildFilter(),
            };

            // BeforeBuild
            foreach (var filter in filters)
            {
                filter.BeforeBuild();
            }

            // Prepare build
            foreach (var file in files)
            {
                foreach (var filter in filters)
                {
                    if (filter.Filtered(file))
                    {
                        AssetBundleBuild?buildInfoNullable = filter.PrepareBuild(file);
                        if (buildInfoNullable != null)
                        {
                            var buildInfo = (AssetBundleBuild)buildInfoNullable;
                            buildInfos[file] = buildInfo;
                        }

                        if (filter.BlockOthers)
                        {
                            break;
                        }
                    }
                }
            }
            AssetDatabase.Refresh();

            try
            {
                var filteredBuildInfos = new List <AssetBundleBuild>();

                // Real build
                var overrideFilters = new HashSet <ResAbstractBuildFilter>();
                foreach (var pair in buildInfos)
                {
                    var filepath  = pair.Key;
                    var buildInfo = pair.Value;

                    var overrided = false;
                    foreach (var filter in filters)
                    {
                        overrided |= filter.OverrideBuild(filepath, buildInfo);
                        if (overrided)
                        {
                            overrideFilters.Add(filter);
                            if (filter.BlockOthers)
                            {
                                break;
                            }
                        }
                    }

                    if (overrided == false)
                    {
                        // Add dependent buildInfos
                        ResBuildUtility.AppendDependencies(buildInfo, filteredBuildInfos);

                        // Add self buildInfo
                        filteredBuildInfos.Add(buildInfo);
                    }
                }

                // Build override filters first
                foreach (var filter in overrideFilters)
                {
                    filter.DoOverrideBuild(_outPath, filteredBuildInfos);
                }

                // Build
                var options = BuildAssetBundleOptions.DeterministicAssetBundle;
                BuildPipeline.BuildAssetBundles(
                    _outPath,
                    filteredBuildInfos.ToArray(),
                    options,
                    targetPlatform
                    );
            }
            catch (Exception e)
            {
                LogManager.Error(e.Message);
            }
            finally
            {
                // After build
                foreach (var filter in filters)
                {
                    filter.AfterBuild();
                }
                AssetDatabase.RemoveUnusedAssetBundleNames();
                AssetDatabase.Refresh();
            }
        }
 static void BuildBundlesWebGL()
 {
     BuildPipeline.BuildAssetBundles("AssetsBundles", BuildAssetBundleOptions.None, BuildTarget.WebGL);
 }
Пример #21
0
    public static void BuildBlockCategroy(int categoryId, string platform)
    {
        string categoryDir = Application.dataPath + "/BlockRes/BlockModels/Category_" + categoryId;


        string refPath = Application.dataPath + "/BlockRes/BlockModels/";


        DirectoryInfo fbxDirInfo = new DirectoryInfo(Path.Combine(categoryDir, "Block_Fbxs"));

        var fileInfos = fbxDirInfo.GetFiles().Where(s => s.Name.ToLower().EndsWith(".fbx"));

        foreach (FileInfo fileInfo in fileInfos)
        {
            SetABName(fileInfo, refPath);
        }

        DirectoryInfo prefabDirInfo = new DirectoryInfo(Path.Combine(categoryDir, "Block_Prefabs"));

        fileInfos = prefabDirInfo.GetFiles().Where(s => s.Name.ToLower().EndsWith(".prefab"));
        foreach (FileInfo fileInfo in fileInfos)
        {
            SetABName(fileInfo, refPath);
        }


        DirectoryInfo thumbDirInfo = new DirectoryInfo(Path.Combine(categoryDir, "Block_Thumbs"));

        fileInfos = thumbDirInfo.GetFiles().Where(s => s.Name.ToLower().EndsWith(".png"));
        foreach (FileInfo fileInfo in fileInfos)
        {
            SetABName(fileInfo, refPath);
        }


        string        materialsPath = "Assets/BlockRes/BlockModels/Category_" + categoryId + "/Block_Materials";
        AssetImporter matAI         = AssetImporter.GetAtPath(materialsPath);

        matAI.assetBundleName = "Category_" + categoryId + "/Block_Materials";


        string        shadersPath = "Assets/BlockRes/BlockModels/Category_" + categoryId + "/Block_Shaders";
        AssetImporter shaderAI    = AssetImporter.GetAtPath(shadersPath);

        shaderAI.assetBundleName = "Category_" + categoryId + "/Block_Shaders";

        SetShareContent(categoryId);



        AssetDatabase.Refresh();

        string destDir = "blocks_" + platform;
        string abPath  = Path.Combine(Application.streamingAssetsPath, destDir);

//		string abPath = Application.streamingAssetsPath+"/blocks_ios";
        if (!Directory.Exists(abPath))
        {
            Directory.CreateDirectory(abPath);
        }
        BuildPipeline.BuildAssetBundles(abPath, BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);

        MoveBundleInfoToCatetory(destDir, categoryId);

        GenerateInfoFile(categoryId, destDir);

        AssetDatabase.Refresh();
    }
 static void BuildBundlesWindows()
 {
     BuildPipeline.BuildAssetBundles("AssetsBundles", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
 }
Пример #23
0
    static void SetUIAssetBundleSelect()
    {
        string        uiPath       = Application.dataPath + "/UIAsset/chart";
        string        uiPath1      = Application.dataPath + "/UIAsset/font";
        string        uiPath2      = Application.dataPath + "/UIAsset/Prefabs";
        string        uiPath3      = Application.dataPath + "/UIAsset/texture";
        string        uiPath4      = Application.dataPath + "/UIAsset/material";
        string        uiPath5      = Application.dataPath + "/UIAsset/shader";
        List <string> filePathList = new List <string>();

        Utility.GetDeepAssetPaths(uiPath, filePathList, "", false, false, true);
        Utility.GetDeepAssetPaths(uiPath1, filePathList, "", false, false, true);
        Utility.GetDeepAssetPaths(uiPath2, filePathList, "", false, false, true);
        Utility.GetDeepAssetPaths(uiPath3, filePathList, "", false, false, true);
        Utility.GetDeepAssetPaths(uiPath4, filePathList, "", false, false, true);
        Utility.GetDeepAssetPaths(uiPath5, filePathList, "", false, false, true);
        List <string> list = new List <string>();

        foreach (var cur in filePathList)
        {
            if (cur.Contains("/UIAsset/Prefabs") && Selection.activeGameObject != null)
            {
                string fName = Utility.GetFileName(cur);
                if (fName == Selection.activeGameObject.name)
                {
                    list.Add(cur);
                    string[] dependFileList = AssetDatabase.GetDependencies(cur);

                    foreach (var df in dependFileList)
                    {
                        if (filePathList.Contains(df))
                        {
                            if (!list.Contains(df))
                            {
                                list.Add(df);
                            }
                        }
                    }
                    break;
                }
            }
        }
        List <AssetBundleBuild> abuildList = new List <AssetBundleBuild>();

        foreach (var cur in list)
        {
            string aName    = cur.Replace("Assets/UIAsset/", "").ToLower();
            string fileName = Utility.GetFileName(cur);
            aName = Utility.GetPathWithExtend(aName);
            AssetImporter importer = AssetImporter.GetAtPath(cur);
            if (importer != null)
            {
                if (cur.Contains("/UIAsset/Prefabs"))
                {
                    aName = "ui/" + fileName.ToLower();
                }
            }
            AssetBundleBuild buildMap = new AssetBundleBuild();
            buildMap.assetBundleName = aName;
            string[] enemyAssets = new string[1];
            enemyAssets[0]      = cur;
            buildMap.assetNames = enemyAssets;
            abuildList.Add(buildMap);
        }
        string outPath = uiAssetBundlesPath + "Select/";

        Utility.DetectCreateDirectory(outPath);
        EditorUtility.DisplayProgressBar("正在启动选中资源打Assetbundle逻辑,请稍等", "正在启动打Assetbundle逻辑,请稍等...", 1);
        BuildPipeline.BuildAssetBundles(outPath, abuildList.ToArray(), BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);
        EditorUtility.ClearProgressBar();
        Utility.Open(outPath);
    }
 static void BuildBundlesMacOS()
 {
     BuildPipeline.BuildAssetBundles("AssetsBundles", BuildAssetBundleOptions.None, BuildTarget.StandaloneOSX);
 }
Пример #25
0
        public static IEnumerator BuildResAsync(IList <string> assets, IEditorWorkProgressShower winprog, IList <IResBuilderEx> runOnceExBuilder)
        {
            bool isDefaultBuild = assets == null;
            var  logger         = new EditorWorkProgressLogger()
            {
                Shower = winprog
            };
            bool shouldCreateBuildingParams = BuildingParams == null;

            BuildingParams = BuildingParams ?? ResBuilderParams.Create();
            var    timetoken = BuildingParams.timetoken;
            var    makezip   = BuildingParams.makezip;
            string outputDir = "Latest";

            if (!isDefaultBuild)
            {
                outputDir = timetoken + "/build";
            }
            outputDir = "EditorOutput/Build/" + outputDir;

            System.IO.StreamWriter swlog = null;
            try
            {
                System.IO.Directory.CreateDirectory(outputDir + "/log/");
                swlog = new System.IO.StreamWriter(outputDir + "/log/ResBuildLog.txt", false, System.Text.Encoding.UTF8);
            }
            catch (Exception e)
            {
                Debug.Log(e);
            }

            EditorApplication.LockReloadAssemblies();
            List <IResBuilderEx> allExBuilders = new List <IResBuilderEx>(ResBuilderEx);

            if (runOnceExBuilder != null)
            {
                allExBuilders.AddRange(runOnceExBuilder);
            }
            Application.LogCallback LogToFile = (message, stack, logtype) =>
            {
                swlog.WriteLine(message);
                swlog.Flush();
            };
            if (swlog != null)
            {
                Application.logMessageReceived += LogToFile;
            }
            for (int i = 0; i < allExBuilders.Count; ++i)
            {
                allExBuilders[i].Prepare(outputDir);
            }
            bool   cleanupDone    = false;
            Action BuilderCleanup = () =>
            {
                if (!cleanupDone)
                {
                    logger.Log("(Phase) Build Res Cleaup.");
                    cleanupDone = true;
                    for (int i = 0; i < allExBuilders.Count; ++i)
                    {
                        allExBuilders[i].Cleanup();
                    }
                    logger.Log("(Done) Build Res Cleaup.");
                    if (swlog != null)
                    {
                        Application.logMessageReceived -= LogToFile;
                        swlog.Flush();
                        swlog.Dispose();

                        if (isDefaultBuild)
                        {
                            var logdir = "EditorOutput/Build/" + timetoken + "/log/";
                            System.IO.Directory.CreateDirectory(logdir);
                            System.IO.File.Copy(outputDir + "/log/ResBuildLog.txt", logdir + "ResBuildLog.txt", true);
                        }
                    }
                    if (shouldCreateBuildingParams)
                    {
                        BuildingParams = null;
                    }
                    EditorApplication.UnlockReloadAssemblies();
                }
            };

            if (winprog != null)
            {
                winprog.OnQuit += BuilderCleanup;
            }

            try
            {
                logger.Log("(Start) Build Res.");
                if (winprog != null && AsyncWorkTimer.Check())
                {
                    yield return(null);
                }

                //logger.Log("(Phase) Ex Full Build System.");
                //for (int i = 0; i < allExBuilders.Count; ++i)
                //{
                //    IEnumerator exwork = allExBuilders[i].CustomBuild();
                //    if (exwork != null)
                //    {
                //        while (exwork.MoveNext())
                //        {
                //            if (winprog != null)
                //            {
                //                yield return exwork.Current;
                //            }
                //        }
                //    }
                //    if (winprog != null && AsyncWorkTimer.Check()) yield return null;
                //}

                // Generate Build Work
                Dictionary <string, CapsResBuildWork> works = new Dictionary <string, CapsResBuildWork>();
                var work = GenerateBuildWorkAsync(works, assets, winprog, runOnceExBuilder);
                while (work.MoveNext())
                {
                    if (winprog != null)
                    {
                        yield return(work.Current);
                    }
                }

                logger.Log("(Phase) Write Manifest.");
                var managermod = CapsEditorUtils.__MOD__;
                var manidir    = "Assets/Mods/" + managermod + "/Build/";
                System.IO.Directory.CreateDirectory(manidir);
                List <AssetBundleBuild> listManiBuilds = new List <AssetBundleBuild>();
                HashSet <string>        maniFileNames  = new HashSet <string>();
                foreach (var kvp in works)
                {
                    foreach (var mani in kvp.Value.Manifests)
                    {
                        var mod  = mani.MFlag;
                        var dist = mani.DFlag;
                        if (winprog != null && AsyncWorkTimer.Check())
                        {
                            yield return(null);
                        }
                        logger.Log("Mod " + mod + "; Dist " + dist);

                        var dmani    = CapsResManifest.Save(mani);
                        var filename = "m-" + mod + "-d-" + dist;
                        var manipath = manidir + filename + ".m.asset";
                        AssetDatabase.CreateAsset(dmani, manipath);

                        maniFileNames.Add(filename.ToLower());
                        listManiBuilds.Add(new AssetBundleBuild()
                        {
                            assetBundleName = filename + ".m.ab", assetNames = new[] { manipath }
                        });
                    }
                }

                logger.Log("(Phase) Build Manifest.");
                if (winprog != null && AsyncWorkTimer.Check())
                {
                    yield return(null);
                }
                var         buildopt   = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression;
                BuildTarget buildtar   = EditorUserBuildSettings.activeBuildTarget;
                var         outmanidir = outputDir + "/res/mani";
                System.IO.Directory.CreateDirectory(outmanidir);
                BuildPipeline.BuildAssetBundles(outmanidir, listManiBuilds.ToArray(), buildopt, buildtar);

                logger.Log("(Phase) Delete Unused Manifest.");
                if (winprog != null && AsyncWorkTimer.Check())
                {
                    yield return(null);
                }
                var manifiles = PlatDependant.GetAllFiles(outmanidir);
                for (int i = 0; i < manifiles.Length; ++i)
                {
                    var file = manifiles[i];
                    if (file.EndsWith(".m.ab"))
                    {
                        var filename = file.Substring(outmanidir.Length + 1, file.Length - outmanidir.Length - 1 - ".m.ab".Length);
                        if (!maniFileNames.Contains(filename))
                        {
                            PlatDependant.DeleteFile(file);
                            PlatDependant.DeleteFile(file + ".manifest");
                        }
                    }
                }

                logger.Log("(Phase) Real Build.");
                foreach (var kvp in works)
                {
                    var mod = kvp.Key;
                    var abs = kvp.Value.ABs;
                    logger.Log("Mod " + mod);
                    if (winprog != null && AsyncWorkTimer.Check())
                    {
                        yield return(null);
                    }

                    var dest = outputDir + "/res";
                    if (!string.IsNullOrEmpty(mod))
                    {
                        dest += "/mod/" + mod;
                    }

                    System.IO.Directory.CreateDirectory(dest);
                    // delete the unused ab
                    HashSet <string> buildFiles = new HashSet <string>();
                    for (int i = 0; i < abs.Length; ++i)
                    {
                        if (!kvp.Value.ForceRefreshABs.Contains(i))
                        {
                            if (string.IsNullOrEmpty(abs[i].assetBundleVariant))
                            {
                                buildFiles.Add(abs[i].assetBundleName.ToLower());
                            }
                            else
                            {
                                buildFiles.Add(abs[i].assetBundleName.ToLower() + "." + abs[i].assetBundleVariant.ToLower());
                            }
                        }
                    }
                    var files = System.IO.Directory.GetFiles(dest);
                    for (int i = 0; i < files.Length; ++i)
                    {
                        var file = files[i];
                        if (!file.EndsWith(".ab"))
                        {
                            var sub   = System.IO.Path.GetFileName(file);
                            var split = sub.LastIndexOf(".ab.");
                            if (split < 0)
                            {
                                continue;
                            }
                            var ext = sub.Substring(split + ".ab.".Length);
                            if (ext.Contains("."))
                            {
                                continue;
                            }
                            if (ext == "manifest")
                            {
                                continue;
                            }
                        }
                        {
                            var fileName = System.IO.Path.GetFileName(file);
                            if (!buildFiles.Contains(fileName))
                            {
                                PlatDependant.DeleteFile(file);
                                PlatDependant.DeleteFile(file + ".manifest");
                            }
                        }
                    }

                    BuildPipeline.BuildAssetBundles(dest, abs, buildopt, buildtar);
                }

                logger.Log("(Phase) Delete Mod Folder Not Built.");
                var outmoddir = outputDir + "/res/mod/";
                if (System.IO.Directory.Exists(outmoddir))
                {
                    var builtMods           = new HashSet <string>(works.Keys);
                    var allModFolders       = System.IO.Directory.GetDirectories(outmoddir);
                    int deletedModFolderCnt = 0;
                    for (int i = 0; i < allModFolders.Length; ++i)
                    {
                        if (winprog != null && AsyncWorkTimer.Check())
                        {
                            yield return(null);
                        }
                        var modfolder = allModFolders[i];
                        logger.Log(modfolder);
                        var mod = modfolder.Substring(outmoddir.Length);
                        if (!builtMods.Contains(mod))
                        {
                            System.IO.Directory.Delete(modfolder, true);
                            ++deletedModFolderCnt;
                        }
                    }
                    if (deletedModFolderCnt == allModFolders.Length)
                    {
                        System.IO.Directory.Delete(outmoddir, true);
                    }
                }

                if (isDefaultBuild)
                {
                    logger.Log("(Phase) Write Version.");
                    var outverdir = outputDir + "/res/version.txt";
                    int version   = GetResVersion();
                    System.IO.File.WriteAllText(outverdir, version.ToString());
                }

                logger.Log("(Phase) Copy.");
                var outresdir     = outputDir + "/res/";
                var allbuildfiles = PlatDependant.GetAllFiles(outresdir);
                if (System.IO.Directory.Exists("Assets/StreamingAssets/res/"))
                {
                    logger.Log("Delete old.");
                    var allexistfiles = PlatDependant.GetAllFiles("Assets/StreamingAssets/res/");
                    for (int i = 0; i < allexistfiles.Length; ++i)
                    {
                        if (winprog != null && AsyncWorkTimer.Check())
                        {
                            yield return(null);
                        }
                        PlatDependant.DeleteFile(allexistfiles[i]);
                    }
                }
                for (int i = 0; i < allbuildfiles.Length; ++i)
                {
                    if (winprog != null && AsyncWorkTimer.Check())
                    {
                        yield return(null);
                    }
                    var srcfile = allbuildfiles[i];
                    if (srcfile.EndsWith(".manifest"))
                    {
                        continue;
                    }
                    var part = srcfile.Substring(outresdir.Length);
                    if (part == "mani/mani")
                    {
                        continue;
                    }
                    logger.Log(part);
                    var destfile = "Assets/StreamingAssets/res/" + part;
                    PlatDependant.CreateFolder(System.IO.Path.GetDirectoryName(destfile));
                    System.IO.File.Copy(srcfile, destfile);
                }

                if (System.IO.Directory.Exists("Assets/StreamingAssets/res/mod/"))
                {
                    logger.Log("(Phase) Delete StreamingAssets Mod Folder Not Built.");
                    var builtMods           = new HashSet <string>(works.Keys);
                    var allModFolders       = System.IO.Directory.GetDirectories("Assets/StreamingAssets/res/mod/");
                    int deletedModFolderCnt = 0;
                    for (int i = 0; i < allModFolders.Length; ++i)
                    {
                        if (winprog != null && AsyncWorkTimer.Check())
                        {
                            yield return(null);
                        }
                        var modfolder = allModFolders[i];
                        logger.Log(modfolder);
                        var mod = modfolder.Substring("Assets/StreamingAssets/res/mod/".Length);
                        if (!builtMods.Contains(mod))
                        {
                            System.IO.Directory.Delete(modfolder, true);
                            ++deletedModFolderCnt;
                        }
                    }
                    if (deletedModFolderCnt == allModFolders.Length)
                    {
                        System.IO.Directory.Delete("Assets/StreamingAssets/res/mod/", true);
                    }
                }

                if (isDefaultBuild && makezip)
                {
                    logger.Log("(Phase) Zip.");
                    List <Pack <string, string, IList <string> > > zips = new List <Pack <string, string, IList <string> > >();
                    var outzipdir = "EditorOutput/Build/" + timetoken + "/whole/res/";
                    System.IO.Directory.CreateDirectory(outzipdir);
                    foreach (var kvp in works)
                    {
                        var mod   = kvp.Key;
                        var manis = kvp.Value.Manifests;
                        for (int i = 0; i < manis.Length; ++i)
                        {
                            var opmod = manis[i].MFlag;
                            var dist  = manis[i].DFlag;
                            if (winprog != null && AsyncWorkTimer.Check())
                            {
                                yield return(null);
                            }
                            logger.Log("Mod " + opmod + "; Dist " + dist);

                            List <string> entries = new List <string>();
                            // abs
                            var abdir = outputDir + "/res";
                            if (!string.IsNullOrEmpty(mod))
                            {
                                abdir += "/mod/" + mod;
                            }

                            if (System.IO.Directory.Exists(abdir))
                            {
                                try
                                {
                                    var files = System.IO.Directory.GetFiles(abdir);
                                    for (int j = 0; j < files.Length; ++j)
                                    {
                                        var file = files[j];
                                        if (!file.EndsWith(".ab"))
                                        {
                                            var sub   = System.IO.Path.GetFileName(file);
                                            var split = sub.LastIndexOf(".ab.");
                                            if (split < 0)
                                            {
                                                continue;
                                            }
                                            var ext = sub.Substring(split + ".ab.".Length);
                                            if (ext.Contains("."))
                                            {
                                                continue;
                                            }
                                            if (ext == "manifest")
                                            {
                                                continue;
                                            }
                                        }
                                        {
                                            var bundle = file.Substring(abdir.Length + 1);
                                            if (IsBundleInModAndDist(bundle, opmod, dist))
                                            {
                                                var entry = file.Substring(outputDir.Length + 1);
                                                entries.Add(entry);
                                                entries.Add(entry + ".manifest");
                                            }
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    logger.Log("(Error)(Not Critical)");
                                    logger.Log(e.ToString());
                                }
                            }
                            if (entries.Count > 0)
                            {
                                // unity build mani
                                var umani = abdir + "/" + (string.IsNullOrEmpty(mod) ? "res" : mod);
                                umani = umani.Substring(outputDir.Length + 1);
                                entries.Add(umani);
                                entries.Add(umani + ".manifest");
                                // mani
                                var mani = "m-" + opmod.ToLower() + "-d-" + dist.ToLower() + ".m.ab";
                                mani = "res/mani/" + mani;
                                entries.Add(mani);
                                entries.Add(mani + ".manifest");
                                entries.Add("res/mani/mani");
                                entries.Add("res/mani/mani.manifest");
                                // version
                                entries.Add("res/version.txt");

                                var zipfile = outzipdir + "m-" + opmod + "-d-" + dist + ".zip";
                                zips.Add(new Pack <string, string, IList <string> >(zipfile, outputDir, entries));
                                //var workz = MakeZipAsync(zipfile, outputDir, entries, winprog);
                                //while (workz.MoveNext())
                                //{
                                //    if (winprog != null)
                                //    {
                                //        yield return workz.Current;
                                //    }
                                //}
                            }
                        }
                    }
                    if (zips.Count > 0)
                    {
                        var workz = CapsResBuilder.MakeZipsBackground(zips, winprog);
                        while (workz.MoveNext())
                        {
                            if (winprog != null)
                            {
                                yield return(workz.Current);
                            }
                        }
                    }
                }

                for (int i = 0; i < allExBuilders.Count; ++i)
                {
                    allExBuilders[i].OnSuccess();
                }
            }
            finally
            {
                BuilderCleanup();
                logger.Log("(Done) Build Res.");
            }
        }
 static void BuildBundles()
 {
     BuildPipeline.BuildAssetBundles("AssetsBundles", BuildAssetBundleOptions.None, BuildTarget.Android);
 }
Пример #27
0
    void OnGUI()
    {
        if (m_modSave == null)
        {
            m_modSave = (DinoModSave)EditorGUIUtility.Load("Assets/Resources/modInfo.asset") as DinoModSave;
        }
        if (m_modSave == null)
        {
            m_modSave = CreateInstance <DinoModSave>();
            Debug.Log("Creating Mod save file");
            if (!Directory.Exists("Assets/Resources/"))
            {
                Directory.CreateDirectory("Assets/Resources/");
            }
            AssetDatabase.CreateAsset(m_modSave, "Assets/Resources/modInfo.asset");
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        var style = new GUIStyle(GUI.skin.label)
        {
            alignment = TextAnchor.MiddleLeft
        };

        m_modSave.m_previewImage = (Texture2D)EditorGUILayout.ObjectField("Preview Image(1mb max)", m_modSave.m_previewImage, typeof(Texture2D), false);
        if (m_modSave.m_previewImage != null)
        {
            try
            {
                m_modSave.m_previewImage.GetPixels32();
            }
            catch (UnityException e)
            {
                if (e != null)
                {
                }
                SetTextureImporterFormat(m_modSave.m_previewImage, true);
            }
        }

        GUILayout.Label("Base Settings", EditorStyles.boldLabel);

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Mod Name", style);
        m_modSave.m_name = GUILayout.TextField(m_modSave.m_name);
        EditorGUILayout.EndHorizontal();

        GUILayout.Label("Mod Description", EditorStyles.boldLabel);

        m_modSave.m_des = GUILayout.TextArea(m_modSave.m_des, GUILayout.Height(100));


        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Mod Count", style);

        string exportCountStr = (GUILayout.TextField(m_modSave.m_expotCount.ToString()));
        int    result         = 0;
        int    arrayCount     = m_modSave.m_expotCount;

        if (int.TryParse(exportCountStr, out result))
        {
            m_modSave.m_expotCount = result;
        }
        m_modSave.m_expotCount = Mathf.Clamp(m_modSave.m_expotCount, 1, 1000);
        EditorGUILayout.EndHorizontal();

        if (m_modSave.m_exportList.Count == 0)
        {
            m_modSave.m_exportList = new List <GameObject>();
            m_modSave.m_exportList.Add(null);
        }
        if (arrayCount != m_modSave.m_exportList.Count)
        {
            while (m_modSave.m_exportList.Count > arrayCount)
            {
                m_modSave.m_exportList.RemoveAt(m_modSave.m_exportList.Count - 1);
            }
            while (m_modSave.m_exportList.Count < arrayCount)
            {
                m_modSave.m_exportList.Add(null);
            }
        }
        for (int x = 0; x < m_modSave.m_exportList.Count; x++)
        {
            string name = "(Missing DinoAsset Script)";

            if (m_modSave.m_exportList[x])
            {
                DinoAsset meta = m_modSave.m_exportList[x].GetComponent <DinoAsset>();
                if (meta)
                {
                    name = meta.m_name;
                }
            }

            m_modSave.m_exportList[x] = (GameObject)EditorGUILayout.ObjectField(name, m_modSave.m_exportList[x], typeof(GameObject), false);
        }
        if (GUILayout.Button("Save"))
        {
            EditorUtility.SetDirty(m_modSave);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Debug.Log("Saved");
        }

        if (GUILayout.Button("Create/Update Mod"))
        {
            if (m_modSave.m_guid == 0)
            {
                byte[] buffer = System.Guid.NewGuid().ToByteArray();
                m_modSave.m_guid = System.BitConverter.ToInt64(buffer, 0);
            }
            string path = Path.GetFullPath(Application.persistentDataPath + "/../../Washbear/Parkasaurus/Mods/" + m_modSave.m_guid.ToString());

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            GUILayout.Label("Mod Description", EditorStyles.boldLabel);
            int count = m_modSave.m_exportList.Count;
            AssetBundleBuild[] buildMap = new AssetBundleBuild[1];


            List <string> dependencies     = new List <string>();
            List <string> dependenciesName = new List <string>();

            {
                string assetPath = AssetDatabase.GetAssetPath(m_modSave);
                dependenciesName.Add("m_modSave");
                dependencies.Add(assetPath);
                Debug.Log("Adding " + assetPath + " added to mod pack");
            }
            if (m_modSave.m_previewImage)
            {
                string assetPath = AssetDatabase.GetAssetPath(m_modSave.m_previewImage);
                dependencies.Add(assetPath);
                Debug.Log("Adding " + assetPath + " added to mod pack");
            }

            for (int x = 0; x < count; x++)
            {
                string assetPath = AssetDatabase.GetAssetPath(m_modSave.m_exportList[x]);
                dependencies.Add(assetPath);
                Debug.Log("Adding " + assetPath + " added to mod pack");
            }

            buildMap[0].assetBundleName = "mod";
            buildMap[0].assetNames      = dependencies.ToArray();



            BuildPipeline.BuildAssetBundles(path, buildMap, BuildAssetBundleOptions.StrictMode, BuildTarget.StandaloneWindows64);
            Debug.Log("Mod Making Completed to " + path);
            EditorUtility.SetDirty(m_modSave);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
Пример #28
0
        public static void BuildAssetBundles()
        {
            // Choose the output path according to the build target.
            var outputPath = CreateAssetBundleDirectory();

            const BuildAssetBundleOptions options = BuildAssetBundleOptions.ChunkBasedCompression;

            var manifest =
                BuildPipeline.BuildAssetBundles(outputPath, options,
                                                EditorUserBuildSettings.activeBuildTarget);
            var versionsTxt = outputPath + "/versions.txt";
            var versions    = new Dictionary <string, string>();

            LoadVersions(versionsTxt, versions);

            var buildVersions = GetVersions(manifest);

            var updates = new List <string>();

            foreach (var item in buildVersions)
            {
                string hash;
                var    isNew = true;
                if (versions.TryGetValue(item.Key, out hash))
                {
                    if (hash.Equals(item.Value))
                    {
                        isNew = false;
                    }
                }
                if (isNew)
                {
                    updates.Add(item.Key);
                }
            }

            if (updates.Count > 0)
            {
                using (var s = new StreamWriter(File.Open(outputPath + "/updates.txt", FileMode.Append)))
                {
                    s.WriteLine(DateTime.Now.ToFileTime() + ":");
                    foreach (var item in updates)
                    {
                        s.WriteLine(item);
                    }
                    s.Flush();
                    s.Close();
                }

                SaveVersions(versionsTxt, buildVersions);
            }
            else
            {
                Debug.Log("nothing to update.");
            }

            string[] ignoredFiles = { GetPlatformName(), "versions.txt", "updates.txt", "manifest" };

            var files = Directory.GetFiles(outputPath, "*", SearchOption.AllDirectories);

            var deletes = (from t in files
                           let file = t.Replace('\\', '/').Replace(outputPath.Replace('\\', '/') + '/', "")
                                      where !file.EndsWith(".manifest", StringComparison.Ordinal) && !Array.Exists(ignoredFiles, s => s.Equals(file))
                                      where !buildVersions.ContainsKey(file)
                                      select t).ToList();

            foreach (var delete in deletes)
            {
                if (!File.Exists(delete))
                {
                    continue;
                }
                File.Delete(delete);
                File.Delete(delete + ".manifest");
            }

            deletes.Clear();
        }
Пример #29
0
        static void RunAssetBundleBuild(string folder, List <string> environments, List <string> vehicles)
        {
            Directory.CreateDirectory(folder);

            var envManifests     = new List <Manifest>();
            var vehicleManifests = new List <Manifest>();

            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                Debug.LogWarning("Cancelling the build.");
                return;
            }

            var currentScenes = new HashSet <Scene>();

            for (int i = 0; i < EditorSceneManager.loadedSceneCount; i++)
            {
                currentScenes.Add(EditorSceneManager.GetSceneAt(i));
            }

            foreach (var name in environments)
            {
                var scene = Path.Combine("Assets", "External", "Environments", name, $"{name}.{SceneExtension}");

                Scene s = EditorSceneManager.OpenScene(scene, OpenSceneMode.Additive);
                try
                {
                    Manifest?manifest = null;

                    foreach (GameObject root in s.GetRootGameObjects())
                    {
                        MapOrigin origin = root.GetComponentInChildren <MapOrigin>();
                        if (origin != null)
                        {
                            manifest = new Manifest
                            {
                                assetName    = name,
                                bundleGuid   = Guid.NewGuid().ToString(),
                                bundleFormat = BundleConfig.BundleFormatVersion,
                                description  = origin.Description,
                                licenseName  = origin.LicenseName,
                                authorName   = "",
                                authorUrl    = "",
                            };
                            break;
                        }
                    }

                    if (manifest.HasValue)
                    {
                        envManifests.Add(manifest.Value);
                    }
                    else
                    {
                        throw new Exception($"Build failed: MapOrigin on {name} not found. Please add a MapOrigin component.");
                    }
                }
                finally
                {
                    if (!currentScenes.Contains(s))
                    {
                        EditorSceneManager.CloseScene(s, true);
                    }
                }
            }

            foreach (var name in vehicles)
            {
                var         prefab = Path.Combine("Assets", "External", "Vehicles", name, $"{name}.{PrefabExtension}");
                VehicleInfo info   = AssetDatabase.LoadAssetAtPath <GameObject>(prefab).GetComponent <VehicleInfo>();
                if (info == null)
                {
                    throw new Exception($"Build failed: Vehicle info on {name} not found. Please add a VehicleInfo component and rebuild.");
                }

                var manifest = new Manifest
                {
                    assetName    = name,
                    bundleGuid   = Guid.NewGuid().ToString(),
                    bundleFormat = BundleConfig.BundleFormatVersion,
                    description  = info.Description,
                    licenseName  = info.LicenseName,
                    authorName   = "",
                    authorUrl    = "",
                };

                vehicleManifests.Add(manifest);
            }

            foreach (var manifest in envManifests)
            {
                try
                {
                    var sceneAsset = Path.Combine("Assets", "External", "Environments", manifest.assetName, $"{manifest.assetName}.{SceneExtension}");

                    var textureBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_textures",
                        assetNames      = AssetDatabase.GetDependencies(sceneAsset).Where(a => a.EndsWith(".png") || a.EndsWith(".jpg")).ToArray(),
                    };

                    var windowsBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_main_windows",
                        assetNames      = new[] { sceneAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, windowsBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneWindows64);

                    var linuxBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_environment_main_linux",
                        assetNames      = new[] { sceneAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, linuxBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneLinux64);

                    File.WriteAllText(Path.Combine(folder, "manifest"), new Serializer().Serialize(manifest));
                    try
                    {
                        using (ZipFile archive = ZipFile.Create(Path.Combine(folder, $"environment_{manifest.assetName}")))
                        {
                            archive.BeginUpdate();
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, textureBuild.assetBundleName)), textureBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, linuxBuild.assetBundleName)), linuxBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, windowsBuild.assetBundleName)), windowsBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, "manifest")), "manifest", CompressionMethod.Stored, true);
                            archive.CommitUpdate();
                            archive.Close();
                        }
                    }
                    finally
                    {
                        File.Delete(Path.Combine(folder, "manifest"));
                    }
                }
                finally
                {
                    var di = new DirectoryInfo(folder);

                    var files = di.GetFiles($"{manifest.bundleGuid}*");
                    Array.ForEach(files, f => f.Delete());

                    files = di.GetFiles($"AssetBundles*");
                    Array.ForEach(files, f => f.Delete());
                }
            }

            foreach (var manifest in vehicleManifests)
            {
                try
                {
                    var prefabAsset = Path.Combine("Assets", "External", "Vehicles", manifest.assetName, $"{manifest.assetName}.{PrefabExtension}");

                    var textureBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_textures",
                        assetNames      = AssetDatabase.GetDependencies(prefabAsset).Where(a => a.EndsWith(".png") || a.EndsWith(".jpg")).ToArray()
                    };

                    var windowsBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_main_windows",
                        assetNames      = new[] { prefabAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, windowsBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneWindows64);

                    var linuxBuild = new AssetBundleBuild()
                    {
                        assetBundleName = $"{manifest.bundleGuid}_vehicle_main_linux",
                        assetNames      = new[] { prefabAsset },
                    };

                    BuildPipeline.BuildAssetBundles(
                        folder,
                        new[] { textureBuild, linuxBuild },
                        BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
                        UnityEditor.BuildTarget.StandaloneLinux64);

                    File.WriteAllText(Path.Combine(folder, "manifest"), new Serializer().Serialize(manifest));
                    try
                    {
                        using (ZipFile archive = ZipFile.Create(Path.Combine(folder, $"vehicle_{manifest.assetName}")))
                        {
                            archive.BeginUpdate();
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, textureBuild.assetBundleName)), textureBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, linuxBuild.assetBundleName)), linuxBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, windowsBuild.assetBundleName)), windowsBuild.assetBundleName, CompressionMethod.Stored, true);
                            archive.Add(new StaticDiskDataSource(Path.Combine(folder, "manifest")), "manifest", CompressionMethod.Stored, true);
                            archive.CommitUpdate();
                            archive.Close();
                        }
                    }
                    finally
                    {
                        File.Delete(Path.Combine(folder, "manifest"));
                    }
                }
                finally
                {
                    var di = new DirectoryInfo(folder);

                    var files = di.GetFiles($"{manifest.bundleGuid}*");
                    Array.ForEach(files, f => f.Delete());

                    files = di.GetFiles($"AssetBundles*");
                    Array.ForEach(files, f => f.Delete());
                }
            }
        }
Пример #30
0
    //-------------------------------------------------------------------------
    static void _buildAssetBundleCompressed(AssetBundleBuild[] arr_abb, string path, BuildTarget target)
    {
        BuildPipeline.BuildAssetBundles(path, arr_abb, BuildAssetBundleOptions.ForceRebuildAssetBundle, target);

        EbLog.Note("Build AssetBundle BuildTarget=" + target);
    }