Пример #1
0
    static void CommandLineBuildAndroid()
    {
        Debug.Log("Command line build Android version\n------------------\n------------------");

        string[] scenes = UnityBuild_HelperMethods.GetBuildScenes();
        string   path   = "D:/Unity Projects/Publishing files/AutomatedUnityBuilds/GameyFire.apk";

        EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, path);
        if (scenes == null || scenes.Length == 0 || path == null)
        {
            return;
        }

        Debug.Log(string.Format("Path: \"{0}\"", path));
        for (int i = 0; i < scenes.Length; ++i)
        {
            Debug.Log(string.Format("Scene[{0}]: \"{1}\"", i, scenes[i]));
        }

        //Debug.Log(string.Format("Creating Directory \"{0}\" if it does not exist", path));
        //(new FileInfo(path)).Directory.Create();

        Debug.Log(string.Format("Switching Build Target to {0}", "Android"));
        EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.Android);

        Debug.Log("Starting Android Build!");
        BuildPipeline.BuildPlayer(scenes, EditorUserBuildSettings.GetBuildLocation(BuildTarget.Android), BuildTarget.Android, BuildOptions.None);
    }
Пример #2
0
        static BuildPlayerOptions GetBuildPlayerOptions(
            bool askForLocation = false,
            BuildPlayerOptions defaultOptions = new BuildPlayerOptions())
        {
            // Fake BuildLocation path to prevent Unity exception
            var activeBuildTarget = EditorUserBuildSettings.activeBuildTarget;
            var buildLocation     = EditorUserBuildSettings.GetBuildLocation(activeBuildTarget);

            // Making sure that current BuildLocation is valid, otherwise create new proper one.
            // New created location will be like: .../<ProjectRoot>/Builds/<BuildTarget>

            switch (InternalEditorUtility.BuildCanBeAppended(activeBuildTarget, buildLocation))
            {
            case CanAppendBuild.No:
            case CanAppendBuild.Unsupported:
                var newBuildLocation = CombinePaths(DefaultBuildLocation, "build");
                EditorUserBuildSettings.SetBuildLocation(activeBuildTarget, newBuildLocation);
                break;
            }

            // Get static internal "GetBuildPlayerOptionsInternal" method and invoke it
            var method = typeof(BuildPlayerWindow.DefaultBuildMethods).GetMethod(
                "GetBuildPlayerOptionsInternal",
                BindingFlags.NonPublic | BindingFlags.Static);

            return((BuildPlayerOptions)method.Invoke(
                       null,
                       new object[] { askForLocation, defaultOptions }));
        }
Пример #3
0
    public static void BuildProject()
    {
        bool abortBuild = false;

        if (System.IO.Directory.Exists(Application.dataPath + "/Scripts/Profiler") &&
            !System.IO.Directory.Exists(Application.dataPath + "/Editor/Profiler"))
        {
            System.IO.Directory.Move(Application.dataPath + "/Scripts/Profiler", Application.dataPath + "/Editor/Profiler");
        }

        if (System.IO.Directory.Exists(Application.dataPath + "/Scripts/Profiler.meta") &&
            !System.IO.Directory.Exists(Application.dataPath + "/Editor/Profiler.meta"))
        {
            System.IO.File.Move(Application.dataPath + "/Scripts/Profiler.meta", Application.dataPath + "/Editor/Profiler.meta");
        }

        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
        string[] scenes = new string[EditorBuildSettings.scenes.Length];
        for (int i = 0; i < scenes.Length; ++i)
        {
            scenes[i] = EditorBuildSettings.scenes[i].path;
        }


#if UNITY_ANDROID
        EditorUserBuildSettings.appendProject = false;

        string savePath = EditorUtility.SaveFilePanel("Build " + BuildTarget.Android,
                                                      EditorUserBuildSettings.GetBuildLocation(BuildTarget.Android), "", "apk");
        if (savePath.Length != 0)
        {
            // Reset build location and name
//	        string dir = System.IO.Path.GetDirectoryName(savePath);
            EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, savePath);
        }
        else
        {
            abortBuild = true;
        }
#else
        EditorUserBuildSettings.appendProject = true;
#endif
        if (!abortBuild)
        {
            UpdateBuildNumber();

            BuildPipeline.BuildPlayer(scenes, EditorUserBuildSettings.GetBuildLocation(EditorUserBuildSettings.activeBuildTarget),
                                      EditorUserBuildSettings.activeBuildTarget, BuildOptions.AcceptExternalModificationsToPlayer);
        }

        //TODO: this is project specific. We should find a way to externalize it from this generic build tool.
        System.IO.Directory.Move(Application.dataPath + "/Editor/Profiler", Application.dataPath + "/Scripts/Profiler");
        System.IO.File.Move(Application.dataPath + "/Editor/Profiler.meta", Application.dataPath + "/Scripts/Profiler.meta");
        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
    }
    public static bool ValidBuildPlayerOptions(bool isBatchMode, ref BuildPlayerOptions options)
    {
        options.targetGroup = BuildPipeline.GetBuildTargetGroup(options.target);
        EditorUserBuildSettings.selectedBuildTargetGroup = options.targetGroup;

        try
        {
            // Path check.
            var askForBuildLocation = true;
            var path = (options.locationPathName ?? "").TrimEnd('/', '\\');
            if (0 < path.Length)
            {
                options.locationPathName = Path.GetFullPath(path);
                askForBuildLocation      = !Directory.Exists(Path.GetDirectoryName(options.locationPathName));
            }


            if (isBatchMode && askForBuildLocation)
            {
                return(false);
            }

            EditorUserBuildSettings.SetBuildLocation(options.target, options.locationPathName);

            var getBuildPlayerOptionsHandler = typeof(BuildPlayerWindow)
                                               .GetField("getBuildPlayerOptionsHandler", BindingFlags.Static | BindingFlags.NonPublic)
                                               .GetValue(null) as Func <BuildPlayerOptions, BuildPlayerOptions>;
            if (getBuildPlayerOptionsHandler != null)
            {
                options = getBuildPlayerOptionsHandler.Invoke(options);
            }
            else
            {
                options = (BuildPlayerOptions)typeof(BuildPlayerWindow.DefaultBuildMethods)
                          .GetMethod("GetBuildPlayerOptionsInternal", BindingFlags.Static | BindingFlags.NonPublic)
                          .Invoke(null, new object[] { askForBuildLocation, options });
            }

            return(true);
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            return(false);
        }
    }
Пример #5
0
    static void iOS()
    {
        string OutputDirName = "shark-bomber-ios";

        string pwd             = Directory.GetCurrentDirectory();
        string workspace       = Directory.GetParent(pwd).ToString();
        string buildOutputPath = Path.Combine(workspace, OutputDirName);

        if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iPhone)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTarget.iPhone);
        }
        BuildOptions customBuildOptions = BuildOptions.None;

        EditorUserBuildSettings.SetBuildLocation(BuildTarget.iPhone, buildOutputPath);
        BuildPipeline.BuildPlayer(getScenes(), buildOutputPath, BuildTarget.iPhone, customBuildOptions);

        Debug.Log(BuildTarget.iPhone.ToString());
    }
Пример #6
0
        private string PickBuildLocation()
        {
            var target       = EditorUserBuildSettings.activeBuildTarget;
            var targetGroup  = BuildPipeline.GetBuildTargetGroup(target);
            var lastLocation = EditorUserBuildSettings.GetBuildLocation(target);
            var extension    = PostprocessBuildPlayer.GetExtensionForBuildTarget(targetGroup, target, BuildOptions.None);
            var defaultName  = FileUtil.GetLastPathNameComponent(lastLocation);

            lastLocation = string.IsNullOrEmpty(lastLocation) ? string.Empty : Path.GetDirectoryName(lastLocation);
            bool updateExistingBuild;
            var  location = EditorUtility.SaveBuildPanel(target, $"{GetBuildText()} {target}", lastLocation, defaultName, extension,
                                                         out updateExistingBuild);

            if (!string.IsNullOrEmpty(location))
            {
                EditorUserBuildSettings.SetBuildLocation(target, location);
            }
            return(location);
        }
Пример #7
0
        /// <summary>
        /// Generates path to builds. Has 2 options:
        /// <list type="bullet">
        ///     <item>
        ///         <description>If result path is the file: <br/><![CDATA[
        ///         <builds_root>/<product_name> <version>[.<target>]/<product_name>[.<specifyName>].<extension>
        ///         ]]> <br/> e.g. <b>/Builds/my_app 2.1.234/my_app.exe</b> or<br/>
        ///         <b>/Builds/my_app 2.1.234.Android/my_app.ARMv7.apk</b>
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <description>If result path is the directory: <br/><![CDATA[
        ///         <builds_root>/<product_name> <version>[.<target>][.<specifyName>]
        ///         ]]> <br/> e.g. <b>/Builds/my_app 2.1.234.iOS</b>
        ///         </description>
        ///     </item>
        /// </list> Where <i>builds_root</i> - build location defined in Unity Build Settings window,
        /// <i>product_name</i> - Product name from Player Settings,
        /// <i>product_name</i> - file extension depending on the target.
        /// If user not define build location for current target, folder panel will open.
        /// </summary>
        /// <param name="target">Target of build</param>
        /// <param name="version">Version of build</param>
        /// <param name="specifyTarget">Default is <i>true</i>. If <i>true</i> then
        /// name of target will be present in the returned path.</param>
        /// <param name="specifyName">Optional</param>
        /// <returns>Generated path to builds</returns>
        /// <exception cref="OperationCanceledException">User closed folder panel.</exception>
        public static string GetBuildPath(BuildTarget target, string version, bool specifyTarget = true, string specifyName = null)
        {
            var pathBuild     = EditorUserBuildSettings.GetBuildLocation(target);
            var fileExtension = BuildLocationFileExtension(target);

            if (string.IsNullOrEmpty(pathBuild))
            {
                var title = string.Format("Select folder for {0} builds for this project", target);
                pathBuild = EditorUtility.OpenFolderPanel(title, "", "");
                if (pathBuild == null)
                {
                    throw new OperationCanceledException("User cancel build");
                }
                if (fileExtension != null)
                {
                    pathBuild += "/" + PlayerSettings.productName + fileExtension;
                }
                EditorUserBuildSettings.SetBuildLocation(target, pathBuild);
            }

            var targetStr  = specifyTarget ? "." + BuiltTargetToPrettyString(target) : "";
            var specifyExt = string.IsNullOrEmpty(specifyName) ? "" : "." + specifyName;

            if (fileExtension != null)
            {
                var pathSeparators = new char[] { '/', '\\' };
                var subLength      = Math.Min(Math.Max(0, pathBuild.LastIndexOfAny(pathSeparators)), pathBuild.Length);
                pathBuild = pathBuild.Substring(0, subLength).TrimEnd(pathSeparators);
                return(string.Format("{0}/{1} {2}{3}/{1}{4}{5}",
                                     pathBuild, PlayerSettings.productName, version, targetStr, specifyExt, fileExtension));
            }
            else
            {
                return(string.Format("{0}/{1} {2}{3}{4}",
                                     pathBuild, PlayerSettings.productName, version, targetStr, specifyExt));
            }
        }
        public void Show()
        {
            string errorMessage = null;

            var buildTarget   = EditorUserBuildSettings.activeBuildTarget;
            var scenes        = EditorBuildSettings.scenes.Select(s => s.path).ToArray();
            var buildLocation = EditorUserBuildSettings.GetBuildLocation(buildTarget);

            if (buildTarget == BuildTarget.StandaloneLinuxUniversal || buildTarget == BuildTarget.StandaloneOSXIntel64)
            {
                OnFailure("Unsupported build target.");
                return;
            }

            if (string.IsNullOrEmpty(buildLocation))
            {
                buildLocation = EditorUtility.SaveFilePanel("Select build location:", "", "", "");
                EditorUserBuildSettings.SetBuildLocation(buildTarget, buildLocation);
                return;
            }

            bool buildDirectoryExists = Directory.Exists(Path.GetDirectoryName(buildLocation));
            bool buildExists          = File.Exists(buildLocation);

            GUILayout.Label(_selectedApp.Value.Name, EditorStyles.centeredGreyMiniLabel);

            if (GUILayout.Button(new GUIContent("←", "Change application"), GUILayout.Width(40)))
            {
                if (OnChangeApp != null)
                {
                    OnChangeApp();
                }
            }
            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                GUILayout.Label("\n                               * Building *\n" +
                                " The project will be built with the following settings. \n", EditorStyles.boldLabel);
                GUILayout.FlexibleSpace();
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Label("Target: " + buildTarget.ToString());
            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label(new GUIContent("Location: " + buildLocation, buildLocation), GUILayout.MaxWidth(300));
                if (GUILayout.Button(new GUIContent("Change", "Change build location")))
                {
                    buildLocation = EditorUtility.SaveFilePanel("Select build location:", "", "", "");
                    EditorUserBuildSettings.SetBuildLocation(buildTarget, buildLocation);
                }
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label("Scenes: ", EditorStyles.boldLabel);
                if (GUILayout.Button(new GUIContent("Edit Scenes", "Button open Build Settings window."), GUILayout.Width(120)))
                {
                    EditorWindow.GetWindow(System.Type.GetType("UnityEditor.BuildPlayerWindow,UnityEditor"));
                }
            }
            EditorGUILayout.EndHorizontal();
            for (int i = 0; i < scenes.Length; i++)
            {
                GUILayout.Label(i + ". " + scenes[i]);
            }
            EditorGUILayout.Separator();
            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
                if (!_buildExecuted && GUILayout.Button(new GUIContent("Build", "Build a new version"), GUILayout.Width(150)))
                {
                    UnityEngine.Debug.Log("Building the player");
                    errorMessage = BuildPipeline.BuildPlayer(scenes, buildLocation, buildTarget, BuildOptions.None);

                    _buildExecuted = true;

                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        if (OnFailure != null)
                        {
                            OnFailure(errorMessage);
                        }
                    }
                    else
                    {
                        if (OnSuccess != null)
                        {
                            OnSuccess();
                        }
                    }
                }
                GUILayout.FlexibleSpace();

                /*
                 * if (buildDirectoryExists && buildExists && GUILayout.Button(new GUIContent("Skip", "Use the last build")))
                 * {
                 *  if (OnSuccess != null)
                 *  {
                 *      OnSuccess();
                 *  }
                 * }
                 */
            }
            EditorGUILayout.EndHorizontal();
        }
        public virtual void OnPreBuild(IStepLocator locator)
        {
            // Опции билдера
            var opts = BuildOptions.None;

            if (Development)
            {
                opts |= BuildOptions.Development;
            }

            if (AllowDebugging)
            {
                opts |= BuildOptions.AllowDebugging | BuildOptions.ConnectWithProfiler;

                if (BuildWithDeepProfilingSupport)
                {
                    opts |= BuildOptions.EnableDeepProfilingSupport;
                }

                if (ScriptsOnlyBuild)
                {
                    opts |= BuildOptions.BuildScriptsOnly;
                }
            }

            if (ShowBuiltPlayer)
            {
                opts |= BuildOptions.ShowBuiltPlayer;
            }

            if (ForceAppendToExistProject)
            {
                opts |= BuildOptions.AcceptExternalModificationsToPlayer;
            }

            if (UseLZ4Compression)
            {
                opts |= BuildOptions.CompressWithLz4;
            }

            if (ServerBuild)
            {
                opts |= BuildOptions.EnableHeadlessMode;
            }

#if UNITY_2021
            EditorUserBuildSettings.il2CppCodeGeneration = Il2CppCodeGeneration;
            PlayerSettings.WebGL.debugSymbolMode         = WebGLDebugSymbolMode;
#endif

#if UNITY_2020_2_OR_NEWER
            SerializedObject projectSettingsManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset")[0]);
            projectSettingsManager.FindProperty("overrideDefaultApplicationIdentifier").boolValue = true;
            projectSettingsManager.ApplyModifiedProperties();
#endif
            EditorUserBuildSettings.waitForManagedDebugger = WaitForManagedDebugger;

#if UNITY_2021_3_OR_NEWER
            EditorUserBuildSettings.standaloneBuildSubtarget = BuildSubTarget;
#endif
            //Scripting options
            var currentBuildTarget = BuildPipeline.GetBuildTargetGroup(BuildTarget);

            PlayerSettings.SetScriptingBackend(currentBuildTarget, ScriptingBackend);
            PlayerSettings.SetApiCompatibilityLevel(currentBuildTarget, ApiCompatibilityLevel);
            PlayerSettings.SetIl2CppCompilerConfiguration(currentBuildTarget, Il2CppCompilerConfiguration);

            PlayerSettings.SetManagedStrippingLevel(currentBuildTarget, CodeStrippingLevel);
            PlayerSettings.stripEngineCode = StripEngineCode;

            // Прописываем bundleId
            PlayerSettings.SetApplicationIdentifier(currentBuildTarget, BundleIdentifier);

            PlayerSettings.gcIncremental             = UseIncrementalGC;
            PlayerSettings.allowUnsafeCode           = AllowUnsafeCode;
            PlayerSettings.bakeCollisionMeshes       = BakeCollisionMeshes;
            PlayerSettings.stripUnusedMeshComponents = StripUnusedMeshComponents;

            PlayerSettings.SetStackTraceLogType(LogType.Assert, AssertStackTraceLogType);
            PlayerSettings.SetStackTraceLogType(LogType.Error, ErrorStackTraceLogType);
            PlayerSettings.SetStackTraceLogType(LogType.Exception, ExceptionStackTraceLogType);
            PlayerSettings.SetStackTraceLogType(LogType.Log, LogStackTraceLogType);
            PlayerSettings.SetStackTraceLogType(LogType.Warning, WarningStackTraceLogType);

            if (string.IsNullOrEmpty(BuildDir))
            {
                BuildDir = EditorUserBuildSettings.GetBuildLocation(BuildTarget);
            }

            // запоминаем директорию сборки
            EditorUserBuildSettings.SetBuildLocation(BuildTarget, BuildDir);

            // Собственно, сборка
            Debug.Log("Full build path: '" + BuildFullPath + "'");
            Directory.CreateDirectory(BuildFullDir);

            if (!DryRun)
            {
#if UNITY_2021_3_OR_NEWER
                BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
                {
                    scenes           = Scenes.ToArray(),
                    locationPathName = BuildFullPath,
                    target           = BuildTarget,
                    subtarget        = ( int )BuildSubTarget,
                    options          = opts,
                };

                var report  = BuildPipeline.BuildPlayer(buildPlayerOptions);
                var summary = report.summary;

                if (summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
                {
                    throw new Exception($"Build failed with {report.summary.totalErrors} errors and {report.summary.totalWarnings} warnings");
                }
#else
                var report = BuildPipeline.BuildPlayer(Scenes.ToArray(), BuildFullPath, BuildTarget, opts);

                if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
                {
                    throw new Exception($"Build failed with {report.summary.totalErrors} errors and {report.summary.totalWarnings} warnings");
                }
#endif
            }
            else
            {
                var scenes  = string.Join(", ", Scenes);
                var optsStr = opts.ToString();
                Debug.Log($"Dry Run selected. Will build player with:\nScenes: {scenes}\nBuildOptions: {optsStr}");
            }
        }
Пример #10
0
    static void CustomBuild(bool runbuild)
    {
        Log("********** STARTING BUILD **********");
        BuildOptions customBuildOptions = BuildOptions.None;

        if (runbuild)
        {
            //set EditorUserBuildSettings.architectureFlags enum flags set buildrun bit on
            if ((customBuildOptions & BuildOptions.AutoRunPlayer) != BuildOptions.AutoRunPlayer)
            {
                customBuildOptions = customBuildOptions | BuildOptions.AutoRunPlayer;
            }
        }
        else
        {
            //set EditorUserBuildSettings.architectureFlags enum flags set showfolder bit on
            if ((customBuildOptions & BuildOptions.ShowBuiltPlayer) != BuildOptions.ShowBuiltPlayer)
            {
                customBuildOptions = customBuildOptions | BuildOptions.ShowBuiltPlayer;
            }
        }
        Log("OPTIONS " + customBuildOptions);
        BuildTarget mycustombuildtarget = EditorUserBuildSettings.activeBuildTarget;
        string      extn = "";

        switch (EditorUserBuildSettings.selectedBuildTargetGroup)
        {
        case BuildTargetGroup.Standalone:
            switch (EditorUserBuildSettings.selectedStandaloneTarget)
            {
            //case BuildTarget.DashboardWidget:
            //	mycustombuildtarget = BuildTarget.DashboardWidget;
            //	extn="wdgt";
            //	break;
            case BuildTarget.StandaloneWindows:
                mycustombuildtarget = BuildTarget.StandaloneWindows;
                extn = "exe";
                break;

            //case BuildTarget.StandaloneWindows64:
            //        mycustombuildtarget=BuildTarget.StandaloneWindows64;
            //        extn="exe";
            //        break;
            case BuildTarget.StandaloneOSXUniversal:
                mycustombuildtarget = BuildTarget.StandaloneOSXUniversal;
                extn = "app";
                break;

            //case BuildTarget.StandaloneOSXPPC:
            //	mycustombuildtarget = BuildTarget.StandaloneOSXPPC;
            //	extn="app";
            //	break;
            case BuildTarget.StandaloneOSXIntel:
                mycustombuildtarget = BuildTarget.StandaloneOSXIntel;
                extn = "app";
                break;
            }
            break;

        case BuildTargetGroup.WebPlayer:
            if (EditorUserBuildSettings.webPlayerStreamed)
            {
                mycustombuildtarget = BuildTarget.WebPlayerStreamed;
                extn = "unity3d";
            }
            else
            {
                mycustombuildtarget = BuildTarget.WebPlayer;
                extn = "unity3d";
            }
            break;

        //case BuildTargetGroup.Wii:
        //	mycustombuildtarget = BuildTarget.Wii;
        //	//extn="???"
        //	break;
        case BuildTargetGroup.iOS:
            mycustombuildtarget = BuildTarget.iOS;
            extn = "xcode";
            break;

        case BuildTargetGroup.PS3:
            mycustombuildtarget = BuildTarget.PS3;
            //extn="???"
            break;

        case BuildTargetGroup.XBOX360:
            mycustombuildtarget = BuildTarget.XBOX360;
            //extn="???"
            break;

        case BuildTargetGroup.Android:
            mycustombuildtarget = BuildTarget.Android;
            extn = "apk";
            break;

        //case BuildTargetGroup.Broadcom:
        //	mycustombuildtarget = BuildTarget.StandaloneBroadcom;
        //	//extn="???"
        //	break;
        case BuildTargetGroup.GLESEmu:
            mycustombuildtarget = BuildTarget.StandaloneGLESEmu;
            //extn="???"
            break;
        }

        Log("TARGET: " + mycustombuildtarget.ToString().ToUpper() + " Extn: " + extn.ToUpper());

        string savepath = EditorUtility.SaveFilePanel("Build " + mycustombuildtarget,
                                                      EditorUserBuildSettings.GetBuildLocation(mycustombuildtarget), "", extn);

        Log("SAVE PATH: " + savepath);

        if (savepath.Length != 0)
        {
            string   dir    = System.IO.Path.GetDirectoryName(savepath);        //get build directory
            string[] scenes = new string[EditorBuildSettings.scenes.Length];
            for (int i = 0; i < EditorBuildSettings.scenes.Length; ++i)
            {
                scenes[i] = EditorBuildSettings.scenes[i].path.ToString();
            }
            ;
            Log("SCENES: " + scenes.Length + "\n" + string.Join("\n", scenes));
            BuildPipeline.BuildPlayer(scenes, savepath, mycustombuildtarget, customBuildOptions);
            EditorUserBuildSettings.SetBuildLocation(mycustombuildtarget, dir);             //store new location for this type of build
        }
        Log("********** BUILD COMPLETED **********");

        if (JuneBuildWindow.GenerateBuildReport)
        {
            string dir             = System.IO.Path.GetDirectoryName(savepath); //get build directory
            string buildReportPath = System.IO.Path.Combine(dir, "BuildReport.html");
            JuneBuildSummary.GenerateBuildReport(buildReportPath, true);
        }

        if (runbuild)
        {
            Log("********** DEPLOYING APPLICATION TO DEVICE **********");
        }
    }
Пример #11
0
        public override void OnFooterGUI()
        {
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("Apply", GUILayout.Height(40)))
            {
                Apply();
            }
            if (GUILayout.Button("Reset", GUILayout.Height(40)))
            {
                Reset();
            }
            EditorGUILayout.BeginVertical();
            if (EditorUserBuildSettings.development)
            {
                MarkError();
            }
            EditorUserBuildSettings.development = EditorGUILayout.Toggle("Development", EditorUserBuildSettings.development);
            ClearError();
            EditorUserBuildSettings.androidBuildSubtarget = (MobileTextureSubtarget)EditorGUILayout.EnumPopup("Texture Compression", EditorUserBuildSettings.androidBuildSubtarget);
            EditorUserBuildSettings.allowDebugging        = EditorGUILayout.Toggle("Script Debugging", EditorUserBuildSettings.allowDebugging);

            EditorGUILayout.BeginHorizontal();
            string buildPath = EditorUserBuildSettings.GetBuildLocation(EditorUserBuildSettings.activeBuildTarget);

            if (File.Exists(buildPath) || Directory.Exists(buildPath))
            {
                MarkError();
            }
            EditorGUILayoutEx.TextField("Build Path", ref buildPath);
            ClearError();

            if (GUILayout.Button("Browse", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                switch (EditorUserBuildSettings.activeBuildTarget)
                {
                case BuildTarget.iOS:
                case BuildTarget.StandaloneOSX:
                    buildPath = EditorUtility.OpenFolderPanel("Build Folder", PathUtil.GetDirectory(buildPath), PathUtil.GetLastDirectory(buildPath));
                    break;

                default:
                    buildPath = EditorUtility.OpenFilePanel("Build Path", PathUtil.GetDirectory(buildPath), "apk");
                    break;
                }
                EditorUserBuildSettings.SetBuildLocation(EditorUserBuildSettings.activeBuildTarget, buildPath);
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
            bool build = GUILayout.Button("Build", GUILayout.Height(40));
            bool run   = GUILayout.Button("Build & Run", GUILayout.Height(40));

            if (build || run)
            {
                BuildOptions buildOptions = BuildOptions.ShowBuiltPlayer | BuildOptions.InstallInBuildFolder;
                if (run)
                {
                    buildOptions |= BuildOptions.AutoRunPlayer;
                }
                if (EditorUserBuildSettings.development)
                {
                    buildOptions |= BuildOptions.Development;
                }
                if (EditorUserBuildSettings.allowDebugging)
                {
                    buildOptions |= BuildOptions.AllowDebugging;
                }
                ReflectionUtil.ExecuteMethod(prebuildMethod);
                AssetDatabase.SaveAssets();

                List <string> scenes = new List <string>();
                foreach (EditorBuildSettingsScene s in EditorBuildSettings.scenes)
                {
                    scenes.Add(s.path);
                }
                BuildPipeline.BuildPlayer(scenes.ToArray(), buildPath, EditorUserBuildSettings.activeBuildTarget, buildOptions);
                ReflectionUtil.ExecuteMethod(postbuildMethod);
            }
            EditorGUILayout.EndHorizontal();
        }
Пример #12
0
    private static bool Make(bool autoRun, string buildNumber, bool makeBundleBasedPlayer, bool includeBundles, bool includeBundlesCache, bool quickPlayer)
    {
        if (makeBundleBasedPlayer)
        {
            if (!EditorApplication.SaveCurrentSceneIfUserWantsTo())
            {
                return(false);
            }
        }

        string buildLocation = EditorUserBuildSettings.GetBuildLocation(BuildUtils.SelectedBuildTarget);

        if (string.IsNullOrEmpty(buildLocation))
        {
            buildLocation = BuildUtils.OpenSaveBuildPanel(BuildUtils.SelectedBuildTarget, "Select build location for " + BuildUtils.SelectedBuildTarget, null, null, null);
        }
        else
        {
            string directory = Path.GetDirectoryName(buildLocation);
            string file      = Path.GetFileNameWithoutExtension(buildLocation);
            string extension = Path.GetExtension(buildLocation);
            if (!string.IsNullOrEmpty(extension))
            {
                extension = extension.Substring(1);                 // Remove the initial dot
            }
            buildLocation = BuildUtils.OpenSaveBuildPanel(BuildUtils.SelectedBuildTarget,
                                                          "Select build location for " + BuildUtils.SelectedBuildTarget, directory, file, extension);
        }

        if (!string.IsNullOrEmpty(buildLocation))
        {
            EditorUserBuildSettings.SetBuildLocation(BuildUtils.SelectedBuildTarget, buildLocation);
        }
        else
        {
            return(false);
        }

        var buildParams = new Builder.Params();

        buildParams.BuildNumber = buildNumber;

        if (autoRun)
        {
            buildParams.Options |= BuildOptions.AutoRunPlayer;
        }
        else
        {
            buildParams.Options |= BuildOptions.ShowBuiltPlayer;
        }

        if (makeBundleBasedPlayer)
        {
            buildParams.ExtraOptions |= Builder.Params.ExtraBuildOptions.BundleBasedPlayer;

            if (includeBundles)
            {
                buildParams.ExtraOptions |= Builder.Params.ExtraBuildOptions.IncludeBundles;
            }

            if (includeBundlesCache)
            {
                buildParams.ExtraOptions |= Builder.Params.ExtraBuildOptions.IncludeBundlesCache;
            }

            if (quickPlayer)
            {
                buildParams.ExtraOptions |= Builder.Params.ExtraBuildOptions.QuickBundlePlayer;
            }
        }

        try
        {
            Build.Make(buildParams);
        }
        catch (System.OperationCanceledException) { }
        catch (Builder.ContinueRequiredException) { }

        return(true);
    }
Пример #13
0
    static void Update()
    {
        if (CheckIfProjectSwitchNeeded())
        {
            return;
        }

        if (EditorApplication.isPlaying)
        {
            if (!AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - Unity is using the project"))
            {
                if (buildNotReady)
                {
                    // do not allow running at an inconsistent state
                    Debug.LogError("Cannot play because MAGIS project is in an inconsistent state. Please fix any issues that weren't resolved by Autorun.CleanUp() and reload the project.");
                    EditorApplication.isPlaying = false;
                    return;
                }
                buildNotReady = true;

                // upon running, hide unnecessary resources
                AssetDatabase.CreateFolder("Assets", "_DO NOT COMMIT RIGHT NOW - Unity is using the project");
                AssetDatabase.Refresh();

                // force editor to play at 1x scale or lower
                Type         type       = typeof(EditorWindow).Assembly.GetType("UnityEditor.GameView");
                EditorWindow w          = EditorWindow.GetWindow(type);
                var          areaField  = type.GetField("m_ZoomArea", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                var          areaObj    = areaField.GetValue(w);
                var          scaleField = areaObj.GetType().GetField("m_Scale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                Vector2      value      = (Vector2)scaleField.GetValue(areaObj);
                if (value.x > 1.0f)
                {
                    scaleField.SetValue(areaObj, new Vector2(1.0f, 1.0f));
                }

                loadedLevel = null;
                if (GameObject.FindWithTag("ARMarker") != null && GameObject.FindWithTag("AREngine") == null)
                {
                    // temporarily halt the loading of an AR editor level to load CommonScene
                    loadedLevel = SceneManager.GetActiveScene().name;
                    SceneManager.LoadScene("CommonScene");
                    DeviceInput.RequestCameraPermission();
                    Debug.Log("Starting ARScene");
                }
                else if (GameObject.Find("GameState") == null)
                {
                    // for other levels that come with arengine, always run from the beginning
                    if (SceneManager.GetActiveScene().name == "ARScene" ||
                        SceneManager.GetActiveScene().name == "ARSubscene" ||
                        SceneManager.GetActiveScene().name == "CommonScene" ||
                        SceneManager.GetActiveScene().name == "TitleScene" ||
                        SceneManager.GetActiveScene().name == "MapScene" ||
                        SceneManager.GetActiveScene().name == "")
                    {
                        SceneManager.LoadScene("CommonScene");
                        Debug.Log("Starting MAGIS from the title screen");
                    }
                }
            }
            else if (buildNotReady && loadedLevel != null)
            {
                // actually load the current editor level, and also load ARScene automatically if needed
                SceneManager.LoadScene(loadedLevel);
                SceneManager.LoadScene("ARScene", LoadSceneMode.Additive);
                loadedLevel = null;
            }
        }
        else if (!EditorApplication.isPlaying && !EditorApplication.isCompiling && !EditorApplication.isUpdating)
        {
            // automatically switch target to iOS or Android if the current target is Windows, macOS, etc.
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iOS &&
                EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
            {
                buildNotReady = true;
                if ((int)System.Environment.OSVersion.Platform == 4 || (int)System.Environment.OSVersion.Platform == 6)
                {
                    EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.iOS, BuildTarget.iOS);
                }
                else
                {
                    EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
                }
                return;
            }
            else
            {
                if (!EditorUserBuildSettings.GetBuildLocation(BuildTarget.iOS).EndsWith("ios_" + DeviceInput.GameName()))
                {
                    EditorUserBuildSettings.development = true;
                }
                EditorUserBuildSettings.buildAppBundle = !EditorUserBuildSettings.development;
                EditorUserBuildSettings.SetBuildLocation(BuildTarget.iOS, "ios_" + DeviceInput.GameName());
                if (EditorUserBuildSettings.buildAppBundle)
                {
                    EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "aab_" + DeviceInput.GameName() + ".aab");
                }
                else
                {
                    EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "apk_" + DeviceInput.GameName() + ".apk");
                }
            }

            // fix to remove empty .fbm folders that create spurious meta files
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            foreach (string asset in AssetDatabase.FindAssets(".fbm"))
            {
                string folder = AssetDatabase.GUIDToAssetPath(asset);
                if (AssetDatabase.IsValidFolder(folder))
                {
                    if (AssetDatabase.FindAssets("t:Object", new[] { folder }).Length == 0)
                    {
                        buildNotReady = true;
                        Debug.Log("Deleting empty folder " + folder);
                        AssetDatabase.DeleteAsset(folder);
                    }
                }
            }

            // fix to remove extraneous _TerrainAutoUpgrade
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            if (AssetDatabase.IsValidFolder("Assets/_TerrainAutoUpgrade"))
            {
                buildNotReady = true;
                Debug.Log("Deleting migration folder _TerrainAutoUpgrade");
                AssetDatabase.DeleteAsset("Assets/_TerrainAutoUpgrade");
            }

            CleanUp();
        }
        else
        {
            buildNotReady = true;
        }
    }
Пример #14
0
        public virtual void OnPreBuild(IStepLocator locator)
        {
            // Опции билдера
            var opts = BuildOptions.None;

            if (Development)
            {
                opts |= BuildOptions.Development;
            }

            if (AllowDebugging)
            {
                opts |= BuildOptions.AllowDebugging | BuildOptions.ConnectWithProfiler;
            }

            if (ShowBuiltPlayer)
            {
                opts |= BuildOptions.ShowBuiltPlayer;
            }

            if (ForceAppendToExistProject)
            {
                opts |= BuildOptions.AcceptExternalModificationsToPlayer;
            }

            if (UseLZ4Compression)
            {
                opts |= BuildOptions.CompressWithLz4;
            }

#if UNITY_2020_2_OR_NEWER
            SerializedObject projectSettingsManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset")[0]);
            projectSettingsManager.FindProperty("overrideDefaultApplicationIdentifier").boolValue = true;
            projectSettingsManager.ApplyModifiedProperties();
#endif

            // Прописываем bundleId
            PlayerSettings.SetApplicationIdentifier(BuildPipeline.GetBuildTargetGroup(BuildTarget), BundleIdentifier);

            if (string.IsNullOrEmpty(BuildDir))
            {
                BuildDir = EditorUserBuildSettings.GetBuildLocation(BuildTarget);
            }

            // запоминаем директорию сборки
            EditorUserBuildSettings.SetBuildLocation(BuildTarget, BuildDir);

            // Собственно, сборка
            Debug.Log("Full build path: '" + BuildFullPath + "'");
            Directory.CreateDirectory(BuildFullDir);

            if (!DryRun)
            {
                var report = BuildPipeline.BuildPlayer(Scenes.ToArray(), BuildFullPath, BuildTarget, opts);

                if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
                {
                    throw new Exception($"Build failed with {report.summary.totalErrors} errors and {report.summary.totalWarnings} warnings");
                }
            }
            else
            {
                var scenes  = string.Join(", ", Scenes);
                var optsStr = opts.ToString();
                Debug.Log($"Dry Run selected. Will build player with:\nScenes: {scenes}\nBuildOptions: {optsStr}");
            }
        }
Пример #15
0
        public virtual bool Build(BuildOptions PlatformSpecificOptions)
        {
            if (!IgorAssert.EnsureTrue(this, GetAndroidSDKPath(this) != "", "Android SDK path is not set!"))
            {
                return(true);
            }

            PlayerSettings.Android.keystorePass = GetParamOrConfigString(AndroidKeystorePassFlag, "Your Android Keystore Password isn't set!  We won't be able to sign your application!");
            PlayerSettings.Android.keyaliasPass = GetParamOrConfigString(AndroidKeyAliasPassFlag, "Your Android Key Alias Password isn't set!  We won't be able to sign your application!");

            if (PlayerSettings.Android.keystorePass == "" || PlayerSettings.Android.keyaliasPass == "")
            {
                return(true);
            }

            FixReadOnlyFilesIn3rdPartyLibs();

            string AndroidProjDirectory = Path.Combine(Path.GetFullPath("."), "Android");

            if (AndroidProjDirectory.Contains(" "))
            {
                AndroidProjDirectory = Path.Combine(Path.GetTempPath() + PlayerSettings.productName, "Android");
            }

            if (Directory.Exists(AndroidProjDirectory))
            {
                IgorRuntimeUtils.DeleteDirectory(AndroidProjDirectory);
            }

            string FullBuiltPath = System.IO.Path.Combine(System.IO.Path.GetFullPath("."), GetBuiltNameForTarget(BuildTarget.Android));

            if (File.Exists(FullBuiltPath))
            {
                IgorRuntimeUtils.DeleteFile(FullBuiltPath);
            }

            // We need to force create the directory before we use it or it will prompt us for a path to build to
            Directory.CreateDirectory(AndroidProjDirectory);

            Log("Android project destination directory is: " + AndroidProjDirectory);

            EditorUserBuildSettings.symlinkLibraries             = true;
            EditorUserBuildSettings.exportAsGoogleAndroidProject = true;

            EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, AndroidProjDirectory);

            BuildOptions AllOptions = PlatformSpecificOptions | BuildOptions.AcceptExternalModificationsToPlayer;

            AllOptions |= GetExternalBuildOptions(JobBuildTarget);

            BuildPipeline.BuildPlayer(IgorUtils.GetLevels(), AndroidProjDirectory, BuildTarget.Android, AllOptions);

            CopyActivityOverrideSourceFiles(AndroidProjDirectory);

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

            BuiltFiles.Add(AndroidProjDirectory);

            IgorCore.SetNewModuleProducts(BuiltFiles);

            Log("Android Eclipse project has been created.");

            return(true);
        }