static void Build() { var globalSettings = GetGlobalSettings(); // Use this for real release builds - more compression, but much slower build // var mainBundle = BuildOptions.None; // var assetBundle = BuildAssetBundleOptions.None; var mainBundle = BuildOptions.CompressWithLz4; var assetBundle = BuildAssetBundleOptions.ChunkBasedCompression; int count = UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; var scenes = new string[] { // only main scene UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(0), UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(1) }; var target = EditorUserBuildSettings.activeBuildTarget; var location = GetBuildDestination(); //Back up initial graphics settings var graphicsSettingsPath = Path.Combine(Path.Combine(Directory.GetParent(Application.dataPath).ToString(), "ProjectSettings"), "GraphicsSettings.asset"); var backup = File.ReadAllText(graphicsSettingsPath); //Change shader inclusion settings for specific target ChangeShaderInclusionSettings(globalSettings.shaderInclusionSettings, GlobalSettings.BundleBuildTarget(target)); string oldText = ""; try { if (!SkipAssetBundles()) { BuildScript.BuildAssetBundles( globalSettings.assetBundleSettings, assetBundle, Path.Combine(Directory.GetParent(location).ToString(), "AssetBundles"), target ); } UpdateBuildInfo(out oldText); BuildPipeline.BuildPlayer(scenes, location, target, mainBundle); } finally { if (oldText != "") { ResetBuildInfo(oldText); } //Reset graphics settings to initial status File.WriteAllText(graphicsSettingsPath, backup); } var files = new string[] { "Map.txt" }; var source = Application.dataPath + "/../"; var destination = Directory.GetParent(location) + "/"; foreach (var f in files) { string srcFilePath = source + f; string destFolderPath = destination + f; if (File.Exists(srcFilePath) && Directory.Exists(destFolderPath)) { FileUtil.CopyFileOrDirectory(srcFilePath, destFolderPath); } } }
static void BuildPlayer() { BuildScript.BuildPlayer(); }
static public void SetAssetBundlesVariantsAndName() { BuildScript.SetAssetBundlesVariantsAndName(); }
static public void ClearExtendsFloder() { BuildScript.ClearExtendsFloder(); }
public override void OnInspectorGUI() { base.OnInspectorGUI(); GUILayoutOption[] guiOpts = new GUILayoutOption[] { GUILayout.Width(80), GUILayout.ExpandWidth(true), }; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Name", guiOpts); EditorGUILayout.LabelField("Include", guiOpts); EditorGUILayout.LabelField("preDownload", guiOpts); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("All", guiOpts); var allIncludeTmp = EditorGUILayout.Toggle("", allInclude, guiOpts); if (allIncludeTmp != allInclude) { allInclude = allIncludeTmp; foreach (var i in mDirs) { mDirs[i.Key].include = allIncludeTmp; } } var allPreDownloadTmp = EditorGUILayout.Toggle("", allPreDownload, guiOpts); if (allPreDownloadTmp != allPreDownload) { allPreDownload = allPreDownloadTmp; foreach (var i in mDirs) { mDirs[i.Key].preDownload = allPreDownloadTmp; } } EditorGUILayout.EndHorizontal(); allInclude = mDirs.Where(i => i.Value.include).Count() == mBehavior.mDirs.Count(); allPreDownload = mDirs.Where(i => i.Value.preDownload).Count() == mBehavior.mDirs.Count(); foreach (var i in mDirs) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(i.Key.Replace("Assets/ABResources/", " "), guiOpts); mDirs[i.Key].include = EditorGUILayout.Toggle("", i.Value.include, guiOpts); mDirs[i.Key].preDownload = EditorGUILayout.Toggle("", i.Value.preDownload, guiOpts); EditorGUILayout.EndHorizontal(); } var rect = EditorGUILayout.GetControlRect(); if (GUI.Button(rect.Split(0, 4), "Refresh")) { Refresh(); } if (GUI.Button(rect.Split(1, 4), "BAndroid")) { foreach (var i in mDirs.Where(ii => ii.Value.include)) { BuildScript.BuildBundle(i.Key, i.Key.Replace("Assets/ABResources/", ""), BuildTarget.Android); } } //if(GUI.Button(rect.Split(2, 4), "Clean Build")) //{ //} if (GUI.changed) { mBehavior.mDirs = mDirs.Values.ToArray(); EditorUtility.SetDirty(mBehavior); //AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } }
static public void DeleteAssetBundlesName() { BuildScript.DeleteAssetBundlesName(); }
static public void AddOnlyInclusionFiles() { BuildScript.AddOnlyInclusionFiles(false); }
private void Start(string[] args) { CurrentTask.Events += new SourceError((code, location, message, objects) => { location = location ?? SourceLocation.Unknowns; Console.WriteLine("{0}:Error {1}:{2}", location.FirstOrDefault(), code, message.format(objects)); return(true); }); CurrentTask.Events += new SourceWarning((code, location, message, objects) => { location = location ?? SourceLocation.Unknowns; Console.WriteLine("{0}:Warning {1}:{2}", location.FirstOrDefault(), message.format(objects)); return(false); }); CurrentTask.Events += new SourceDebug((code, location, message, objects) => { location = location ?? SourceLocation.Unknowns; Console.WriteLine("{0}:DebugMessage {1}:{2}", location.FirstOrDefault(), code, message.format(objects)); return(false); }); CurrentTask.Events += new Error((code, message, objects) => { Console.WriteLine("{0}:Error {1}", code, message.format(objects)); return(true); }); CurrentTask.Events += new Warning((code, message, objects) => { Console.WriteLine("{0}:Warning {1}", code, message.format(objects)); return(false); }); CurrentTask.Events += new Debug((code, message, objects) => { Console.WriteLine("{0}:DebugMessage {1}", code, message.format(objects)); return(false); }); CurrentTask.Events += new Verbose((code, message, objects) => { Console.WriteLine("{0}:Verbose {1}", code, message.format(objects)); return(false); }); CurrentTask.Events += new Message((code, message, objects) => { Console.WriteLine("{0}:Message {1}", code, message.format(objects)); return(false); }); #if true try { Environment.CurrentDirectory = @"C:\root\V2\coapp-packages\openssl\copkg"; Console.WriteLine("Package script"); using (var script = new PackageScript("openssl.autopkg")) { IEnumerable <string> overlayFiles; var pkgFile = script.Save(PackageTypes.NuGet, false, false, out overlayFiles); } Console.WriteLine(); } catch (Exception e) { Console.WriteLine("{0} =>\r\n\r\nat {1}", e.Message, e.StackTrace.Replace("at ClrPlus.Scripting.Languages.PropertySheetV3.PropertySheetParser", "PropertySheetParser")); } #else try { // Environment.CurrentDirectory = @"C:\project"; Console.WriteLine("Build script"); using (var script = new BuildScript("test.buildinfo")) { script.Execute(); } } catch (Exception e) { Console.WriteLine("{0} =>\r\n\r\nat {1}", e.Message, e.StackTrace.Replace("at ClrPlus.Scripting.Languages.PropertySheetV3.PropertySheetParser", "PropertySheetParser")); } #endif return; // }
static public void AddFirstLoadFiles() { BuildScript.FirstLoadFiles(false); }
static public void AddExtensionFiles() { BuildScript.ExtensionFiles(false); }
public override BuildScript GetBuildScript() { /// <summary> /// A script that checks that the C# extractor has been executed. /// </summary> BuildScript CheckExtractorRun(bool warnOnFailure) => BuildScript.Create(actions => { if (actions.FileExists(Extractor.GetCSharpLogPath())) { return(0); } if (warnOnFailure) { Log(Severity.Error, "No C# code detected during build."); } return(1); }); var attempt = BuildScript.Failure; switch (GetCSharpBuildStrategy()) { case CSharpBuildStrategy.CustomBuildCommand: attempt = new BuildCommandRule(DotNetRule.WithDotNet).Analyse(this, false) & CheckExtractorRun(true); break; case CSharpBuildStrategy.Buildless: // No need to check that the extractor has been executed in buildless mode attempt = new StandaloneBuildRule().Analyse(this, false); break; case CSharpBuildStrategy.MSBuild: attempt = new MsBuildRule().Analyse(this, false) & CheckExtractorRun(true); break; case CSharpBuildStrategy.DotNet: attempt = new DotNetRule().Analyse(this, false) & CheckExtractorRun(true); break; case CSharpBuildStrategy.Auto: var cleanTrapFolder = BuildScript.DeleteDirectory(TrapDir); var cleanSourceArchive = BuildScript.DeleteDirectory(SourceArchiveDir); var tryCleanExtractorArgsLogs = BuildScript.Create(actions => { foreach (var file in Extractor.GetCSharpArgsLogs()) { try { actions.FileDelete(file); } catch // lgtm[cs/catch-of-all-exceptions] lgtm[cs/empty-catch-block] { } } return(0); }); var attemptExtractorCleanup = BuildScript.Try(cleanTrapFolder) & BuildScript.Try(cleanSourceArchive) & tryCleanExtractorArgsLogs & BuildScript.DeleteFile(Extractor.GetCSharpLogPath()); /// <summary> /// Execute script `s` and check that the C# extractor has been executed. /// If either fails, attempt to cleanup any artifacts produced by the extractor, /// and exit with code 1, in order to proceed to the next attempt. /// </summary> BuildScript IntermediateAttempt(BuildScript s) => (s & CheckExtractorRun(false)) | (attemptExtractorCleanup & BuildScript.Failure); attempt = // First try .NET Core IntermediateAttempt(new DotNetRule().Analyse(this, true)) | // Then MSBuild (() => IntermediateAttempt(new MsBuildRule().Analyse(this, true))) | // And finally look for a script that might be a build script (() => new BuildCommandAutoRule(DotNetRule.WithDotNet).Analyse(this, true) & CheckExtractorRun(true)) | // All attempts failed: print message AutobuildFailure(); break; } return(attempt); }
// ビルド前処理 public void OnPreprocessBuild(UnityEditor.BuildTarget target, string path) { if (target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneWindows64) { EditDirectory.Delete(Application.dataPath + "/../" + Path.Combine(BuildScript.BUILD_PROJECT_DIRECTORY, BuildScript.GetPlatformFolderForAssetBundles(target))); } // 引数取得 string[] args = System.Environment.GetCommandLineArgs(); int i, len = args.Length; for (i = 0; i < len; ++i) { switch (args[i]) { case "/branch": case "/debug_message": break; case "build_target": if (args[i + 1] == "ios") { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.iOS, BuildTarget.iOS); } break; case "target_env": if (args[i + 1] == "development") { PlayerSettings.productName = string.Format("Dev{0}", PlayerSettings.productName); PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, PlayerSettings.applicationIdentifier + ".development"); } break; case "build_number": PlayerSettings.iOS.buildNumber = args[i + 1]; break; } } }
public static bool BuildGame(GameBuilderParameter para) { Debug.Log("Build Game Start and Para is:" + para); if (!para.BuildVersion.CheckConstraint()) { Debug.LogError("BuildVersion not pass constraint! version:" + para.BuildVersion.GetVersionString()); return(false); } try { if (para.BuildTarget == BuildTarget.iOS) { para.UseMono2X = false; Debug.Log("ios platform always use IL2ccpp. is not will compiler error"); } // 处理热更url if (!HandleHotFix(para)) { return(false); } Debug.Log("Clear " + Application.streamingAssetsPath); FileUtils.ClearDirectoryReadOnly(Application.streamingAssetsPath); FileUtils.ClearDirectory(Application.streamingAssetsPath); SetupSetting(para); // build lua bundle Debug.Log("Start MarkBundlesNames "); ToLuaMenu.MarkBundlesNames(); Debug.Log("End MarkBundlesNames "); if (para.ApplyAllRule) { Debug.Log("Start ApplyAllRule "); AssetBundleRuleUtils.ApplyAll(null, true); Debug.Log("ApplyAllRule finish "); } string sourcePath = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName()); if (!para.IncreativeBuildAssetBundles) { Debug.Log("Clear Assetbundle dir:" + sourcePath); FileUtils.ClearDirectoryReadOnly(sourcePath); FileUtils.ClearDirectory(sourcePath); Debug.Log("finish Clear Assetbundle dir:"); } Debug.Log("BuildAssetBundles to " + sourcePath); BuildScript.BuildAssetBundles(null, para.BundleCompress ? ToLuaMenu.GetBuildAssetBundleOptions(): BuildAssetBundleOptions.None); Debug.Log("BuildAssetBundles finish "); Debug.Log("Start CopyDirectory to Streaming"); FileUtils.CopyDirectory(sourcePath, VersionConst.StreamingVersionPath); Debug.Log("Finish CopyDirectory to Streaming"); // 这个放在下面,不然会被前面的删除掉 if (para.CopyFmod) { // -音效引擎相关代码,放在打包资源之后因为会清理打包资源-// Debug.Log("CopyToStreamingAssets---------------------------------------"); //EventManager.DoCopyToStreamingAssets(); Debug.Log("MasterBankName---------------------------------------"); } Debug.Log("GenHotFixFileListAndCheckConflict"); AssetBundleRuleUtils.GenHotFixFileListAndCheckConflict(); bool bOk = true; if (para.BuildMode == BuildMode.Patch || para.BuildMode == BuildMode.All) { Debug.Log("开始生成补丁"); VersionPatchBuilder patchBuilder = new VersionPatchBuilder(para.BuildTarget, para.BuildVersion, para.BuildNumber); if (!patchBuilder.Build()) { bOk = false; } Debug.Log("结束生成补丁"); } // 如果要求生成补丁,但补丁失败,则包也 if (bOk && (para.BuildMode == BuildMode.Package || para.BuildMode == BuildMode.All)) { Debug.Log("开始写入发布时版本信息:" + VersionConst.ReleasedVersionPath); // 写入发布版本信息 SaveReleasedVersionFile(para.BuildVersion, VersionConst.ReleasedVersionPath); Debug.Log("结束写入发布时版本信息"); Debug.Log("开始生成安装包"); string[] levels = BuilderEditorUtils.GetBuildScenes(); var error = BuildPipeline.BuildPlayer(levels , para.OutputPath , para.BuildTarget , para.BuildOptions); if (!string.IsNullOrEmpty(error)) { Debug.LogError("Build failed: " + error); bOk = false; } Debug.Log("结束生成安装包"); } return(bOk); } catch (Exception e) { Debug.LogError("error BuildGame stderror exception: " + e.Message); return(false); } }
public void PreVisit(BuildScript buildScript) { sb.AppendFormat("{0} {{", buildScript.Resource); }
static public void RemoveExtensionFiles() { BuildScript.ExtensionFiles(true); }
void OnGUI() { var customButton = new GUIStyle("Button"); GUIStyle customLabel; customLabel = new GUIStyle("Label"); customLabel.fixedHeight = 50; GUI.Box(new Rect(0, 0, 50, 50), new GUIContent("", logotex), customLabel); Rect r = (Rect)EditorGUILayout.BeginVertical(customLabel); customLabel = new GUIStyle("Label"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 14; customLabel.normal.textColor = Color.black; customLabel.fontStyle = FontStyle.Bold; GUILayout.Label("Custom Avatar Builder", customLabel); customLabel = new GUIStyle("Label"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 11; customLabel.normal.textColor = new Color(0.5f, 0.5f, 0.5f); customLabel.fontStyle = FontStyle.Bold; GUILayout.Label("Version: 1.0.3", customLabel); EditorGUILayout.EndVertical(); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 14; customLabel.normal.textColor = new Color(0.0f, 0.0f, 1.0f); customLabel.fontStyle = FontStyle.Bold; EditorGUILayout.LabelField("Select the .blend file to process:"); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 10; customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f); customLabel.fontStyle = FontStyle.Italic; customLabel.fixedWidth = 100; customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 14; customLabel.normal.textColor = new Color(0.0f, 0.0f, 1.0f); customLabel.fontStyle = FontStyle.Bold; if (GUILayout.Button("Import Avatar Model", customLabel)) { if (characterType == (int)ArmatureLinker.CharacterType.DEFAULT) { var enumName = System.Enum.GetName(typeof(ArmatureLinker.CharacterType), ArmatureLinker.CharacterType.DEFAULT); Debug.LogError(string.Format("You must specify a character type (\"{0}\" is not a valid selection)", enumName)); EditorUtility.DisplayDialog("Error", string.Format("Character type: \"{0}\" is not a valid selection!\n\nPlease select a desired character type first.", enumName), "Ok"); return; } if (!string.IsNullOrEmpty(blenderAppPath) && !File.Exists(blenderAppPath)) { EditorUtility.DisplayDialog("Blender Application Is Not Set", "Please browse for and select the installed Blender application. Must be version 2.79.", "OK"); return; } AssetDatabase.RemoveUnusedAssetBundleNames(); var modelPath = EditorUtility.OpenFilePanel(string.Format("Load {0} model", getCharacterTypesArray[characterType].ToLower()), modelPathLast, "blend"); if (!string.IsNullOrEmpty(modelPath)) { modelPathLast = Path.GetDirectoryName(modelPath); if (Path.GetExtension(modelPath).Equals(".blend")) { if (!RunBatch(AnimPrepAssetPostprocessor.AssetBundleVariant, modelPath, blenderAppPath)) { EditorUtility.DisplayDialog("No AssetCreator.exe Tool", "Please ensure the AssetCreator.exe tool in located in the AnimPrep directory.", "OK"); return; } var baseName = Path.GetFileNameWithoutExtension(modelPath); modelPath = Path.Combine( Path.Combine( Path.GetDirectoryName(modelPath), baseName.ToLower() + string.Format("_{0}", AnimPrepAssetPostprocessor.AssetBundleVariant.ToLower()) ), baseName + ".fbx" ); } var uploadFolder = Path.GetDirectoryName(modelPath); //var userName = Path.GetFileName (SystemInfo.deviceName); var uploadFolderTop = new DirectoryInfo(uploadFolder).Name; var uploadName = System.Guid.NewGuid().ToString(); // Path.GetFileName (uploadFolder); var processingPath = AnimPrepAssetPostprocessor.processingFolder; // Path.Combine(Application.dataPath, "MakeHumanModels"); //processingPath = Path.Combine (processingPath, userName); processingPath = Path.Combine(processingPath, uploadName); System.IO.Directory.CreateDirectory(processingPath); DirectoryInfo dir = new DirectoryInfo(uploadFolder); FileInfo[] modelsInfo = dir.GetFiles("*.fbx"); if (modelsInfo.Length == 0) { Debug.LogError("modelsInfo was empty. No .fbx file could be loaded."); return; } string uid = uploadName.Replace(AnimPrepAssetPostprocessor.templateSeperator.ToString(), ""); // uploadFolderTop.Replace("$", ""); //Copy all model files foreach (FileInfo f in modelsInfo) { var to = Path.Combine( processingPath, AnimPrepAssetPostprocessor.AssetBundleVariant + AnimPrepAssetPostprocessor.templateSeperator + //"$" uid + AnimPrepAssetPostprocessor.templateSeperator + //"$" f.Name ); FileUtil.CopyFileOrDirectory(f.FullName, to); } //Copy all .json files FileInfo[] jsonInfo = dir.GetFiles("*.json"); foreach (FileInfo f in jsonInfo) { var to = Path.Combine(processingPath, f.Name); FileUtil.CopyFileOrDirectory(f.FullName, to); } //Copy all images files string[] extensions = new[] { ".png", ".jpg", ".tiff", ".bmp" }; DirectoryInfo dir_images = new DirectoryInfo(Path.Combine(uploadFolder, "textures")); FileInfo[] texturesInfo = dir_images.GetFiles() .Where(f => extensions.Contains(f.Extension.ToLower())) .ToArray(); foreach (FileInfo f in texturesInfo) { var to = Path.Combine(processingPath, f.Name); FileUtil.CopyFileOrDirectory(f.FullName, to); } AnimPrepAssetPostprocessor.AssetBundleUserJson userPrefs = new AnimPrepAssetPostprocessor.AssetBundleUserJson() { created = System.DateTime.UtcNow, variantTag = getCharacterTypesArray[characterType], //use the index of the users selection to get then enum name from the chracter types // AnimPrepAssetPostprocessor.ReallusionAssetVariantTag, //user = userName, //uploadFolder = uploadName, characterFolder = Path.GetDirectoryName(modelPath) }; string json = JsonUtility.ToJson(userPrefs); var jsonPath = Path.Combine(AnimPrepAssetPostprocessor.assetBundlesFolder, uid + ".json"); using (StreamWriter sr = new StreamWriter(jsonPath)) { // Create the file. sr.WriteLine(json); } AssetDatabase.Refresh(); BuildScript.BuildAssetBundles(); AssetDatabase.Refresh(); Debug.Log(string.Format("Created new {0} character!\nPress \"Append Prefabs To Scene\" button to see the newly created character.", getCharacterTypesArray[characterType].ToLower())); } } GUILayout.BeginHorizontal(); characterType = EditorGUILayout.Popup("Character Type:", characterType, getCharacterTypesArray, GUILayout.MinWidth(100)); GUILayout.EndHorizontal(); EditorGUILayout.Space(); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 14; customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f); customLabel.fontStyle = FontStyle.Bold; EditorGUILayout.LabelField("Save changes to assetbundles:"); if (GUILayout.Button("Re-Build Assetbundles", customLabel)) { var allPaths = AssetDatabase.GetAllAssetPaths(); foreach (var assetPath in allPaths) { if (assetPath.StartsWith(AnimPrepAssetPostprocessor.prefabsFolder)) { //ensure the prefab is enabled before saving as assetbundle string modelFileName = Path.GetFileNameWithoutExtension(assetPath); GameObject modelAsset = AssetDatabase.LoadAssetAtPath <GameObject> (assetPath); //LOADING AN ASSET if (modelAsset == null) { continue; } if (!modelAsset.activeSelf) { GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(modelAsset); model.SetActive(true); PrefabUtility.SaveAsPrefabAsset(model, assetPath); GameObject.DestroyImmediate(model); } } } var allShaderKeywordParams = GameObject.FindObjectsOfType <RendererShaderParams> (); foreach (var shaderKeywordParams in allShaderKeywordParams) { shaderKeywordParams.StoreParams(); } var allRootGos = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); foreach (var go in allRootGos) { bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null; if (isPrefabInstance) { RendererShaderParams.StoreAllRenderers(go); PrefabUtility.ReplacePrefab(go, PrefabUtility.GetPrefabParent(go), ReplacePrefabOptions.ConnectToPrefab); } } AssetDatabase.Refresh(); BuildScript.BuildAssetBundles(); AssetDatabase.Refresh(); ShowAssetBundlesExplorer(); } EditorGUILayout.Space(); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 12; //customLabel.normal.textColor = new Color(0.0f,0.5f,0.0f); customLabel.fontStyle = FontStyle.Italic; EditorGUILayout.LabelField("Add processed models to scene:"); if (GUILayout.Button("Append Prefabs To Scene", customLabel)) { //Vector3 offsetSpacing = Vector3.right * 1.5f; var info = new DirectoryInfo(AnimPrepAssetPostprocessor.prefabsFolder); var fileInfo = info.GetFiles("*.prefab", SearchOption.TopDirectoryOnly); for (int i = 0; i < fileInfo.Length; i++) { var file = fileInfo[i]; if (Path.GetExtension(file.FullName).Equals(".meta")) { continue; } string fullPath = file.FullName.Replace(@"\", "/"); string assetPath = "Assets" + fullPath.Replace(Application.dataPath, ""); bool alreadyInScene = false; var allRootGos = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); foreach (var go in allRootGos) { bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null; if (isPrefabInstance) { Object parentObject = EditorUtility.GetPrefabParent(go); string path = AssetDatabase.GetAssetPath(parentObject); if (assetPath.Equals(path)) { alreadyInScene = true; break; } } } if (alreadyInScene) { continue; } UnityEngine.Object prefab = AssetDatabase.LoadMainAssetAtPath(assetPath); GameObject clone = PrefabUtility.InstantiatePrefab(prefab as GameObject) as GameObject; //clone.transform.position = offsetSpacing * i; } } EditorGUILayout.Space(); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 12; customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f); customLabel.fontStyle = FontStyle.Italic; EditorGUILayout.LabelField("Show folder containing output files:"); if (GUILayout.Button("Open Assetbundles Folder", customLabel)) { ShowAssetBundlesExplorer(); } EditorGUILayout.Space(); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Blender Application (v2.79):", GUILayout.MinWidth(0)); customLabel = new GUIStyle("Label"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontStyle = FontStyle.BoldAndItalic; if (blenderAppExists) { customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f); EditorGUILayout.LabelField("File Exists", customLabel, GUILayout.Width(100)); } else { customLabel.normal.textColor = new Color(0.5f, 0.0f, 0.0f); EditorGUILayout.LabelField("File Missing!", customLabel, GUILayout.Width(100)); customButton = new GUIStyle("Button"); customButton.alignment = TextAnchor.MiddleCenter; customButton.fontSize = 10; customButton.normal.textColor = new Color(0.2f, 0.2f, 0.2f); customButton.fontStyle = FontStyle.Italic; customButton.fixedWidth = 100; if (GUILayout.Button("Default", customButton)) { blenderAppPath = blenderAppPathDefault; } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); customLabel = new GUIStyle("Button"); customLabel.alignment = TextAnchor.MiddleCenter; customLabel.fontSize = 10; customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f); customLabel.fontStyle = FontStyle.Italic; customLabel.fixedWidth = 100; blenderAppPath = GUILayout.TextField(blenderAppPath, GUILayout.MinWidth(0)); if (GUILayout.Button("Browse", customLabel)) { string modelPath = EditorUtility.OpenFilePanel("Blender Application (v2.79)", Path.GetDirectoryName(blenderAppPath), "exe"); if (!string.IsNullOrEmpty(modelPath)) { blenderAppPath = modelPath; } } GUILayout.EndHorizontal(); if (GUI.changed) { CheckBlenderAppExists(); } this.Repaint(); }
static public void RemapMd5fileName() { BuildScript.RemapMd5fileName(); }
public static BuildResultCode BuildLocal(BuilderOptions options) { string inputFile = options.InputFiles[0]; string sdkDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../.."); BuildScript buildScript = BuildScript.LoadFromFile(sdkDir, inputFile); buildScript.Compile(options.Plugins); if (buildScript.GetWarnings().FirstOrDefault() != null) { foreach (string warning in buildScript.GetWarnings()) { options.Logger.Warning(warning); } } if (buildScript.HasErrors) { foreach (string error in buildScript.GetErrors()) { options.Logger.Error(error); } throw new InvalidOperationException("Can't compile the provided build script."); } string inputDir = Path.GetDirectoryName(inputFile) ?? Environment.CurrentDirectory; options.SourceBaseDirectory = options.SourceBaseDirectory ?? Path.Combine(inputDir, buildScript.SourceBaseDirectory ?? ""); options.BuildDirectory = options.BuildDirectory ?? Path.Combine(inputDir, buildScript.BuildDirectory ?? ""); options.OutputDirectory = options.OutputDirectory ?? (buildScript.OutputDirectory != null ? Path.Combine(inputDir, buildScript.OutputDirectory) : ""); options.MetadataDatabaseDirectory = options.MetadataDatabaseDirectory ?? (buildScript.MetadataDatabaseDirectory != null ? Path.Combine(inputDir, buildScript.MetadataDatabaseDirectory) : ""); if (!string.IsNullOrWhiteSpace(options.SourceBaseDirectory)) { if (!Directory.Exists(options.SourceBaseDirectory)) { string error = string.Format("Source base directory \"{0}\" does not exists.", options.SourceBaseDirectory); options.Logger.Error(error); throw new OptionException(error, "sourcebase"); } Environment.CurrentDirectory = options.SourceBaseDirectory; } if (string.IsNullOrWhiteSpace(options.BuildDirectory)) { throw new OptionException("This tool requires a build path.", "build-path"); } // Mount build path ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(options.BuildDirectory); options.ValidateOptionsForMaster(); // assets is always added by default //options.Databases.Add(new DatabaseMountInfo("/assets")); PrepareDatabases(options); try { VirtualFileSystem.CreateDirectory("/data/"); VirtualFileSystem.CreateDirectory("/data/db/"); } catch (Exception) { throw new OptionException("Invalid Build database path", "database"); } // Create builder LogMessageType logLevel = options.Debug ? LogMessageType.Debug : (options.Verbose ? LogMessageType.Verbose : LogMessageType.Info); var logger = Logger.GetLogger("builder"); logger.ActivateLog(logLevel); var builder = new Builder("builder", options.BuildDirectory, options.BuilderMode, logger) { ThreadCount = options.ThreadCount }; builder.MonitorPipeNames.AddRange(options.MonitorPipeNames); builder.ActivateConfiguration(options.Configuration); foreach (var sourceFolder in buildScript.SourceFolders) { builder.InitialVariables.Add(("SourceFolder:" + sourceFolder.Key).ToUpperInvariant(), sourceFolder.Value); } Console.CancelKeyPress += (sender, e) => Cancel(builder, e); buildScript.Execute(builder); // Run builder return(builder.Run(options.Append == false)); }
static public void AddOnlyInclusionFilesByTxt() { BuildScript.AddOnlyInclusionFilesByTxt(); }
public static void GenerateAssetBundlesUpdateFile(string[] allBundles) { string title = "Generate Update File "; string info = "Compute crc32"; EditorUtility.DisplayProgressBar(title, info, 0.1f); #region 读取首包 CrcCheck.Clear(); bool firstExists = false; DirectoryInfo firstDir = new DirectoryInfo(Application.dataPath); string firstPath = Path.Combine(firstDir.Parent.Parent.FullName, Common.FirstOutPath); string readPath = Path.Combine(firstPath, CUtils.GetAssetPath("")); readPath = Path.Combine(readPath, CUtils.GetRightFileName(Common.CRC32_FILELIST_NAME)); Debug.Log(readPath); WWW abload = new WWW("file://" + readPath); if (string.IsNullOrEmpty(abload.error) && abload.assetBundle != null) { var ab = abload.assetBundle; TextAsset ta = ab.LoadAllAssets <TextAsset>()[0]; //ta.text Debug.Log(ta); string context = ta.text; string[] split = context.Split('\n'); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\[""(.+)""\]\s+=\s+(\d+)"); float j = 1; float l = split.Length; foreach (var line in split) { System.Text.RegularExpressions.Match match = regex.Match(line); if (match.Success) { //Debug.Log(match.Groups[1].Value + " " + match.Groups[2].Value); CrcCheck.Add(match.Groups[1].Value, System.Convert.ToUInt32(match.Groups[2].Value)); } //Debug.Log(line); EditorUtility.DisplayProgressBar(title, "read first crc => " + j.ToString() + "/" + l.ToString(), j / l); j++; } ab.Unload(true); firstExists = true; } else { Debug.LogWarning(abload.error + "no frist packeage in " + readPath); } abload.Dispose(); #endregion #region 生成校验列表 Dictionary <string, uint> updateList = new Dictionary <string, uint>(); StringBuilder sb = new StringBuilder(); sb.AppendLine("return {"); var selected = string.Empty; float i = 0; float allLen = allBundles.Length; //忽略列表 Dictionary <string, bool> ignore = new Dictionary <string, bool>(); ignore.Add(CUtils.GetRightFileName(Common.CRC32_FILELIST_NAME), true); ignore.Add(CUtils.GetRightFileName(Common.CRC32_VER_FILENAME), true); foreach (var str in allBundles) { string url = Path.Combine(CUtils.GetRealStreamingAssetsPath(), str); uint outCrc = 0; Debug.Log(str); string abName = str.Replace("\\", "/"); string key = CUtils.GetAssetBundleName(abName); if (!ignore.ContainsKey(key) && CrcCheck.CheckLocalFileWeakCrc(url, out outCrc) == false) //如果不一致需要更新 { updateList.Add(abName, outCrc); //记录导出记录 sb.AppendLine("[\"" + key + "\"] = " + outCrc + ","); } EditorUtility.DisplayProgressBar(title, info + "=>" + i.ToString() + "/" + allLen.ToString(), i / allLen); i++; } sb.AppendLine("}"); //Debug.Log (sb.ToString ()); CrcCheck.Clear(); //输出到临时目录 var crc32filename = CUtils.GetAssetName(Common.CRC32_FILELIST_NAME); string tmpPath = Path.Combine(Application.dataPath, TmpPath); ExportResources.CheckDirectory(tmpPath); string assetPath = "Assets/" + TmpPath + crc32filename + ".txt"; EditorUtility.DisplayProgressBar("Generate file list", "write file to " + assetPath, 0.99f); string outPath = Path.Combine(tmpPath, crc32filename + ".txt"); Debug.Log("write to path=" + outPath); using (StreamWriter sr = new StreamWriter(outPath, false)) { sr.Write(sb.ToString()); } // //打包到streaming path AssetDatabase.Refresh(); string crc32outfilename = CUtils.GetRightFileName(Common.CRC32_FILELIST_NAME); //(fileCrc32ListName + ".u3d"); BuildScript.BuildABs(new string[] { assetPath }, null, crc32outfilename, BuildAssetBundleOptions.DeterministicAssetBundle); string topath = Path.Combine(GetOutPutPath(), crc32outfilename); Debug.Log(info + " assetbunle build complate! " + topath); #endregion #region 生成版本号 //生成版本号码 string crc32Path = "file://" + Path.Combine(CUtils.GetRealStreamingAssetsPath(), CUtils.GetRightFileName(Common.CRC32_FILELIST_NAME)); //CUtils.GetAssetFullPath (fileCrc32ListName+".u3d"); WWW loaderVer = new WWW(crc32Path); if (!string.IsNullOrEmpty(loaderVer.error)) { Debug.LogError(loaderVer.error); return; } uint crcVer = Crc32.Compute(loaderVer.bytes); loaderVer.Dispose(); tmpPath = CUtils.GetRealStreamingAssetsPath();//Path.Combine (Application.streamingAssetsPath, CUtils.GetAssetPath("")); outPath = Path.Combine(tmpPath, CUtils.GetRightFileName(Common.CRC32_VER_FILENAME)); Debug.Log("verion to path=" + outPath); //json 化version{ code,crc32,version} StringBuilder verJson = new StringBuilder(); verJson.Append("{"); verJson.Append(@"""code"":" + CodeVersion.CODE_VERSION + ","); verJson.Append(@"""crc32"":" + crcVer.ToString() + ","); verJson.Append(@"""time"":" + CUtils.ConvertDateTimeInt(System.DateTime.Now) + ""); verJson.Append("}"); using (StreamWriter sr = new StreamWriter(outPath, false)) { sr.Write(verJson.ToString()); } Debug.Log(info + " Complete! ver=" + crcVer.ToString() + " path " + outPath); BuildScript.BuildAssetBundles(); #endregion #region copy更新文件导出 if (updateList.Count > 0) { info = "copy updated file "; string updateOutPath = Path.Combine(firstPath, CUtils.GetAssetPath("") + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm")); DirectoryInfo outDic = new DirectoryInfo(updateOutPath); if (outDic.Exists) { outDic.Delete(); } outDic.Create(); if (!firstExists) { updateList.Clear(); //如果没有首包,只导出校验文件。 } updateList.Add(CUtils.GetRightFileName(Common.CRC32_VER_FILENAME), 0); updateList.Add(CUtils.GetRightFileName(Common.CRC32_FILELIST_NAME), crcVer); string sourcePath; string outfilePath; i = 1; allLen = updateList.Count; string key = ""; foreach (var k in updateList) { key = CUtils.GetAssetBundleName(k.Key); sourcePath = Path.Combine(CUtils.GetRealStreamingAssetsPath(), k.Key); if (k.Value != 0) { if (key.Equals(CUtils.platformFloder)) { key = key + "_" + k.Value.ToString() + "." + Common.ASSETBUNDLE_SUFFIX; } else { key = CUtils.InsertAssetBundleName(key, "_" + k.Value.ToString());// } } outfilePath = Path.Combine(updateOutPath, key); FileHelper.CheckCreateFilePathDirectory(outfilePath); File.Copy(sourcePath, outfilePath, true);// source code copy EditorUtility.DisplayProgressBar(title, info + "=>" + i.ToString() + "/" + allLen.ToString(), i / allLen); i++; } Debug.Log(" copy file complete!"); } #endregion EditorUtility.ClearProgressBar(); }
static public void ExcludeExtensionFiles() { BuildScript.ExcludeExtensionFiles(); }
static public void SetAssetBundlesName() { BuildScript.SetAssetBundlesName(); }
static public void CheckSelectedAssetbundleSize() { BuildScript.CheckSelectedAssetbundleSize(); }
static public void SetExtendsFloder() { BuildScript.SetAsExtendsFloder(); }
static public void CheckInCludeAssetbundleSize() { BuildScript.CheckInCludeAssetbundleSize(); }
static public void ClearUnUsedAssetBundlesName() { BuildScript.ClearUnUsedAssetBundlesName(); }
static public void CheckFirstAssetbundleSize() { BuildScript.CheckFirstLoaddAssetbundleSize(); }
static public void BuildAssetBundles() { BuildScript.BuildAssetBundles(); }
static public void UpdateAssetBundlesName() { var allAssets = AssetDatabase.GetAllAssetPaths().ToArray(); BuildScript.UpdateAssetBundlesName(allAssets); }
public void PostVisit(BuildScript buildScript) { sb.Replace(',', ' ', sb.Length - 1, 1); sb.AppendFormat("}}{0}", ResourceSeparator); }
static public void GenerateAssetBundlesMd5Mapping() { var allAssets = AssetDatabase.GetAllAssetPaths().ToArray(); BuildScript.GenerateAssetBundlesMd5Mapping(allAssets); }
public override bool Execute() { int buildId; try { dynamic buildEngine = BuildEngine.AccessPrivate(); var host = buildEngine.host; dynamic pHost = new AccessPrivateWrapper(host); var bp = pHost.buildParameters; dynamic pBp = new AccessPrivateWrapper(bp); buildId = pBp.buildId; lock (typeof(InvokeBuild)) { if (buildId <= MaxBuildId) { // this happens when we build a solution, and it wants to build each project return true; } MaxBuildId = buildId; } } catch { } using (new PushDirectory(Environment.CurrentDirectory)) { try { if (Location.Is()) { Environment.CurrentDirectory = Location.GetFullPath(); } if (string.IsNullOrWhiteSpace(ScriptFile)) { // search for it. ScriptFile = new[] { @"copkg\.buildinfo", @"contrib\.buildinfo", @"contrib\coapp\.buildinfo", @".buildinfo" }.WalkUpPaths(); if (string.IsNullOrEmpty(ScriptFile)) { throw new ClrPlusException(@"Unable to find .buildinfo file anywhere in the current directory structure."); } } if (!File.Exists(ScriptFile)) { throw new ClrPlusException(@"Unable to find Invoke-build script file '{0}'.".format(ScriptFile)); } string[] defines = Defines.IsNullOrEmpty() ? new string[0] : Defines.Select(each => each.ItemSpec).ToArray(); using (var buildScript = new BuildScript(ScriptFile)) { buildScript.BuildMessage += message => { try { switch (message.EventType) { case "BuildWarning": Log.LogWarning(message.Subcategory, message.Code, message.HelpKeyword, message.File, message.LineNumber, message.ColumnNumber, message.EndLineNumber, message.EndColumnNumber, message.Message); break; case "BuildError": Log.LogError(message.Subcategory, message.Code, message.HelpKeyword, message.File, message.LineNumber, message.ColumnNumber, message.EndLineNumber, message.EndColumnNumber, message.Message); break; case "ProjectStarted": Log.LogExternalProjectStarted(message.Message, message.HelpKeyword, message.ProjectFile, message.TargetNames); break; case "ProjectFinished": Log.LogExternalProjectFinished(message.Message, message.HelpKeyword, message.ProjectFile, message.Succeeded); break; case "TaskStarted": Log.LogMessage(MessageImportance.Low, message.Message); break; case "TaskFinished": Log.LogMessage(MessageImportance.Low, message.Message); break; case "TargetStarted": Log.LogMessage(MessageImportance.Low, message.Message); break; case "TargetFinished": Log.LogMessage(MessageImportance.Low, message.Message); break; case "BuildStarted": Log.LogMessage(MessageImportance.Low, message.Message); break; case "BuildFinished": Log.LogMessage(MessageImportance.Low, message.Message); break; case "BuildMessage": Log.LogMessage((MessageImportance)message.Importance, message.Message); break; default: Log.LogMessage(MessageImportance.Low, message.Message); break; } } catch (Exception e) { LogError("{0}/{1}/{2}", e.GetType().Name, e.Message, e.StackTrace ); } return false; }; foreach (var i in defines) { var p = i.IndexOf("="); var k = p > -1 ? i.Substring(0, p) : i; var v = p > -1 ? i.Substring(p + 1) : ""; buildScript.AddMacro(k, v); } var targets = Targets.IsNullOrEmpty() ? new string[0] : Targets.Select(each => each.ItemSpec).ToArray(); if (Targets.IsNullOrEmpty()) { targets = new string[] { "default" }; } Environment.SetEnvironmentVariable("MaxThreads", "" + MaxThreads); Environment.SetEnvironmentVariable("HIDE_THREADS", "true"); buildScript.MaxThreads = MaxThreads; return buildScript.Execute(targets); } } catch (Exception e) { LogError("{0}/{1}/{2}".format(e.GetType().Name, e.Message, e.StackTrace)); return false; } finally { Environment.SetEnvironmentVariable("HIDE_THREADS", null); Environment.SetEnvironmentVariable("MaxThreads", null); } } }
public static void exportLua() { checkLuaExportPath(); BuildScript.CheckstreamingAssetsPath(); string info = "luac"; string title = "build lua"; EditorUtility.DisplayProgressBar(title, info, 0); var childrens = AssetDatabase.GetAllAssetPaths().Where(p => (p.StartsWith("Assets/Lua") || p.StartsWith("Assets/Config")) && (p.EndsWith(".lua")) ).ToArray(); string path = "Assets/Lua/"; //lua path string path1 = "Assets/Config/"; //config path string root = Application.dataPath.Replace("Assets", ""); Debug.Log("luajit path = " + luacPath); string crypName = "", fileName = "", outfilePath = "", arg = ""; System.Text.StringBuilder sb = new System.Text.StringBuilder(); //refresh directory DirectoryDelete(Application.dataPath + OutLuaPath); CheckDirectory(Application.dataPath + OutLuaPath); float allLen = childrens.Length; float i = 0; List <string> exportNames = new List <string>(); foreach (string file in childrens) { string filePath = Path.Combine(root, file); fileName = CUtils.GetAssetName(filePath); crypName = file.Replace(path, "").Replace(path1, "").Replace(".lua", "." + Common.LUA_LC_SUFFIX).Replace("\\", "_").Replace("/", "_"); outfilePath = Application.dataPath + OutLuaPath + crypName; exportNames.Add("Assets" + OutLuaPath + crypName); sb.Append(fileName); sb.Append("="); sb.Append(crypName); sb.Append("\n"); #if Nlua || UNITY_IPHONE arg = "-o " + outfilePath + " " + filePath; // luac File.Copy(filePath, outfilePath, true); // source code copy #else arg = "-b " + filePath + " " + outfilePath; //for jit //Debug.Log(arg); //System.Diagnostics.Process.Start(luacPath, arg);//jit File.Copy(filePath, outfilePath, true);// source code copy #endif i++; EditorUtility.DisplayProgressBar(title, info + "=>" + i.ToString() + "/" + allLen.ToString(), i / allLen); } Debug.Log("lua:" + path + "files=" + childrens.Length + " completed"); System.Threading.Thread.Sleep(1000); AssetDatabase.Refresh(); EditorUtility.DisplayProgressBar(title, "build lua", 0.99f); //u5 打包 CheckDirectory(Path.Combine(Application.dataPath, OutLuaPath)); BuildScript.BuildABs(exportNames.ToArray(), "Assets" + OutLuaPath, "luaout.bytes", BuildAssetBundleOptions.DeterministicAssetBundle); EditorUtility.DisplayProgressBar(title, "Encrypt lua", 0.99f); //Encrypt string tarName = Application.dataPath + OutLuaPath + "luaout.bytes"; string md5Name = CUtils.GetRightFileName(Common.LUA_ASSETBUNDLE_FILENAME); string realOutPath = Path.Combine(BuildScript.GetOutPutPath(), md5Name); byte[] by = File.ReadAllBytes(tarName); byte[] Encrypt = CryptographHelper.Encrypt(by, GetKey(), GetIV()); File.WriteAllBytes(realOutPath, Encrypt); Debug.Log(realOutPath + " export"); EditorUtility.ClearProgressBar(); }