コード例 #1
0
        private static void SetupAssemblyReloadEvents()
        {
            // playmodeStateChanged was marked obsolete in 2017.1. Still working in 2018.3
#pragma warning disable 618
            EditorApplication.playmodeStateChanged += () =>
#pragma warning restore 618
            {
                var newPlayModeState = GetPlayModeState();
                if (PlayModeSavedState != newPlayModeState)
                {
                    if (PluginSettings.AssemblyReloadSettings == AssemblyReloadSettings.RecompileAfterFinishedPlaying)
                    {
                        if (newPlayModeState == PlayModeState.Playing)
                        {
                            ourLogger.Info("LockReloadAssemblies");
                            EditorApplication.LockReloadAssemblies();
                        }
                        else if (newPlayModeState == PlayModeState.Stopped)
                        {
                            ourLogger.Info("UnlockReloadAssemblies");
                            EditorApplication.UnlockReloadAssemblies();
                        }
                    }
                    PlayModeSavedState = newPlayModeState;
                }
            };

            AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
            {
                if (PluginSettings.AssemblyReloadSettings == AssemblyReloadSettings.StopPlayingAndRecompile)
                {
                    if (EditorApplication.isPlaying)
                    {
                        EditorApplication.isPlaying = false;
                    }
                }
            };
        }
コード例 #2
0
        /// <summary>
        ///     Downloads and extracts the Core Sdk and associated libraries and tools.
        /// </summary>
        private static DownloadResult Download()
        {
            if (!Common.CheckDependencies())
            {
                return(DownloadResult.Error);
            }

            RemoveMarkerFile();

            int exitCode;

            try
            {
                EditorApplication.LockReloadAssemblies();

                using (new ShowProgressBarScope($"Installing SpatialOS libraries, version {Common.CoreSdkVersion}..."))
                {
                    exitCode = RedirectedProcess.Command(Common.DotNetBinary)
                               .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                               .WithArgs(ConstructArguments())
                               .Run();
                    if (exitCode != 0)
                    {
                        Debug.LogError($"Failed to download SpatialOS Core Sdk version {Common.CoreSdkVersion}. You can use SpatialOS -> Download CoreSDK (force) to retry this.");
                    }
                    else
                    {
                        File.WriteAllText(InstallMarkerFile, string.Empty);
                    }
                }
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }

            return(exitCode == 0 ? DownloadResult.Success : DownloadResult.Error);
        }
コード例 #3
0
 private static void OnToolbarGUI()
 {
     if (!initialized)
     {
         Initialize();
     }
     GUILayout.FlexibleSpace();
     if (GUILayout.Button(content, style))
     {
         if (EditorPrefs.GetBool(PrefsKey))
         {
             EditorApplication.UnlockReloadAssemblies();
             EditorPrefs.SetBool(PrefsKey, false);
             Debug.Log("Unlocked compile");
         }
         else
         {
             EditorApplication.LockReloadAssemblies();
             EditorPrefs.SetBool(PrefsKey, true);
             Debug.Log("Locked compile");
         }
     }
 }
コード例 #4
0
        private static void Prepare()
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                if (!Directory.Exists(InjectionConstants.ResourcesFolder))
                {
                    Directory.CreateDirectory(InjectionConstants.ResourcesFolder);
                }

                File.WriteAllText(InjectionConstants.DataFilePath, "please remove me", Encoding.Unicode);
                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogError(ACTkConstants.LogPrefix + "Injection Detector preparation failed: " + e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #5
0
        static KUnityEditorEventCatcher()
        {
            EditorApplication.update -= OnEditorUpdate;
            EditorApplication.update += OnEditorUpdate;

            SceneView.onSceneGUIDelegate -= OnSceneViewGUI;
            SceneView.onSceneGUIDelegate += OnSceneViewGUI;

            EditorApplication.playmodeStateChanged -= OnPlayModeStateChanged;
            EditorApplication.playmodeStateChanged += OnPlayModeStateChanged;



            if (OnLockingAssembly != null)
            {
                EditorApplication.LockReloadAssemblies();
                OnLockingAssembly();
                EditorApplication.UnlockReloadAssemblies();
            }


            IsInited = true;
        }
コード例 #6
0
        private static void WeaveAssembly(string assemblyPath)
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                UnityEngine.Debug.Log("Start weaving assemblies");

                var stopwatch = Stopwatch.StartNew();
                using (var facade = new BindingFacade())
                {
                    facade.CreateBindingsInAssembly(assemblyPath);
                }

                stopwatch.Stop();

                UnityEngine.Debug.Log($"Finished weaving assemblies in {stopwatch.Elapsed.TotalSeconds} seconds");
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #7
0
        private static void PostCompile()
        {
            EditorApplication.LockReloadAssemblies();
            try
            {
                var mainAssembly   = CecilUtility.GetAssembly("Assembly-CSharp");
                var editorAssembly = CecilUtility.GetAssembly("MCI");
                var engineAssembly = EngineAssemblyDefinition();

                Process(mainAssembly, editorAssembly, engineAssembly);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }

            AssemblyDefinition EngineAssemblyDefinition()
            {
                const string path = "C:\\Program Files\\Unity\\Editor\\Data\\Managed\\UnityEngine.dll";

                return(AssemblyDefinition.ReadAssembly(path));
            }
        }
コード例 #8
0
ファイル: EditorWeaver.cs プロジェクト: D-Bantz/Malimbe
        private static void WeaveAllAssemblies()
        {
            EditorApplication.LockReloadAssemblies();
            bool didChangeAnyAssembly = false;

            try
            {
                IReadOnlyCollection <string> searchPaths = WeaverPathsHelper.GetSearchPaths().ToList();
                Runner runner = new Runner(new Logger());
                runner.Configure(searchPaths, searchPaths);

                foreach (Assembly assembly in GetAllAssemblies())
                {
                    if (!WeaveAssembly(assembly, runner))
                    {
                        continue;
                    }

                    string sourceFilePath = assembly.sourceFiles.FirstOrDefault();
                    if (sourceFilePath == null)
                    {
                        continue;
                    }

                    AssetDatabase.ImportAsset(sourceFilePath, ImportAssetOptions.ForceUpdate);
                    didChangeAnyAssembly = true;
                }
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
                if (didChangeAnyAssembly)
                {
                    AssetDatabase.Refresh();
                }
            }
        }
コード例 #9
0
        private void SetupProjectParameters()
        {
            EditorApplication.LockReloadAssemblies();

            m_EditorBuildSettings = EditorBuildSettings.scenes;

#pragma warning disable 618
            m_DisplayResolutionDialog = PlayerSettings.displayResolutionDialog;
            PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.Disabled;
#pragma warning restore 618

            m_RunInBackground = PlayerSettings.runInBackground;
            PlayerSettings.runInBackground = true;

            m_FullScreenMode = PlayerSettings.fullScreenMode;
            PlayerSettings.fullScreenMode = FullScreenMode.Windowed;

            m_OldAotOptions           = PlayerSettings.aotOptions;
            PlayerSettings.aotOptions = "nimt-trampolines=1024";

            m_ResizableWindow = PlayerSettings.resizableWindow;
            PlayerSettings.resizableWindow = true;

            m_ShowUnitySplashScreen          = PlayerSettings.SplashScreen.show;
            PlayerSettings.SplashScreen.show = false;

            m_OldproductName           = PlayerSettings.productName;
            PlayerSettings.productName = "UnityTestFramework";

#pragma warning disable 618
            m_OldLightmapping           = Lightmapping.giWorkflowMode;
            Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand;
#pragma warning restore 618

            m_explicitNullChecks = EditorUserBuildSettings.explicitNullChecks;
            EditorUserBuildSettings.explicitNullChecks = true;
        }
コード例 #10
0
        /// <summary>
        ///     Downloads and extracts the Core Sdk and associated libraries and tools.
        /// </summary>
        private static DownloadResult Download()
        {
            RemoveMarkerFile();

            int exitCode;

            try
            {
                EditorApplication.LockReloadAssemblies();

                using (new ShowProgressBarScope($"Installing SpatialOS libraries, version {Common.CoreSdkVersion}..."))
                {
                    exitCode = RedirectedProcess.Run(Common.DotNetBinary, ConstructArguments());
                    if (exitCode != 0)
                    {
                        Debug.LogError($"Failed to download SpatialOS Core Sdk version {Common.CoreSdkVersion}. You can use SpatialOS -> Download CoreSDK (force) to retry this.");
                    }
                    else
                    {
                        File.WriteAllText(InstallMarkerFile, string.Empty);
                    }
                }
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }

            if (exitCode != 0)
            {
                return(DownloadResult.Error);
            }

            AssetDatabase.Refresh();
            SetPluginsCompatibility();
            return(DownloadResult.Success);
        }
コード例 #11
0
    static ScriptExecutionOrderHandler()
    {
        if (EditorApplication.isCompiling || EditorApplication.isPaused || EditorApplication.isPlaying)
        {
            return;
        }

        EditorApplication.LockReloadAssemblies();

        // Loop through monoscripts
        foreach (MonoScript monoScript in MonoImporter.GetAllRuntimeMonoScripts())
        {
            Type monoClass = monoScript.GetClass();

            if (monoClass != null)
            {
                Attribute att = Attribute.GetCustomAttribute(monoClass, typeof(ScriptExecutionOrderAttribute));

                if (att != null)
                {
                    int executionIndex = ((ScriptExecutionOrderAttribute)att).executionIndex;

                    // It is important not to set the execution order if the value is already correct!
                    if (MonoImporter.GetExecutionOrder(monoScript) != executionIndex)
                    {
                        MonoImporter.SetExecutionOrder(monoScript, executionIndex);
#if ENABLE_LOGGING
                        Debug.Log("The script " + monoScript.name + " was not set to correct Script Execution Order. It has been fixed and set to " + executionIndex + ".");
#endif
                    }
                }
            }
        }

        EditorApplication.UnlockReloadAssemblies();
    }
コード例 #12
0
        //----- property -----

        //----- method -----

        protected void OnAssemblyReload()
        {
            if (Prefs.RequestCompile)
            {
                RequestCompile();
            }
            else
            {
                var json = Prefs.Result;

                if (!string.IsNullOrEmpty(json))
                {
                    var results = JsonConvert.DeserializeObject <CompileResult[]>(json);

                    EditorApplication.LockReloadAssemblies();

                    OnCompileFinished(results);

                    EditorApplication.UnlockReloadAssemblies();

                    Prefs.Result = null;
                }
            }
        }
コード例 #13
0
        /**
         * 用于生成上下文代码
         * 因为fairGUI每个component层级深度固定,不会很多层,所以相对清晰
         * 从选中的组件为根节点 递归获取内部引用
         */
        public static void GenerateCtrlPartGen(List <FairyGUI.PackageItem> itemsToGen, FairyGUI.UIPackage pak)
        {
            EditorApplication.LockReloadAssemblies();


            var exportPipeInfo = ParseExportInfo(itemsToGen, pak);

            foreach (var typeExportInfo in exportPipeInfo.ExportComponentInfoMap)
            {
                CodeTemplateFairyGUI.GenerateCustomComponent(typeExportInfo.Key, typeExportInfo.Value, pak.id, pak.name);
            }


            //generate readonly code
            foreach (var typeExportInfo in exportPipeInfo.ExportCustomElementInfoMap)
            {
                CodeTemplateFairyGUI.GenerateCustomElement(typeExportInfo.Key, typeExportInfo.Value, pak.id, pak.name);
            }



            //AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
            UnityEditor.EditorApplication.UnlockReloadAssemblies();
        }
コード例 #14
0
        /**
         * This method restores obfuscated MonoBehaviour cs files to their original names.
         */
        private static void RestoreAssets()
        {
#if UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
#else
            if (BuildPipeline.isBuildingPlayer == false)
            {
#endif
            try
            {
                EditorApplication.LockReloadAssemblies();
                Obfuscator.RevertAssetObfuscation();
                monoBehaviourAssetsNeedReverting = false;
                EditorApplication.update        -= RestoreAssets;
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
#if UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
#else
        }
#endif
            Obfuscator.Clear();
        }
コード例 #15
0
ファイル: Postbuild.cs プロジェクト: Tetta/Solitaire
        public static void Obfuscate()
        {
#if UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
            if (!EditorApplication.isPlayingOrWillChangePlaymode && !_obfuscatedAfterScene && _hasError == false)
#else
            if (!EditorApplication.isPlayingOrWillChangePlaymode && !_obfuscatedAfterScene && _hasError == false && BuildPipeline.isBuildingPlayer)
#endif
            {
                try
                {
                    EditorApplication.LockReloadAssemblies();
                    ObfuscateWhileLocked();
                }
                catch (Exception e)
                {
                    Debug.LogError("Obfuscation Failed: " + e);
                    _hasError = true;
                }
                finally
                {
                    EditorApplication.UnlockReloadAssemblies();
                }
            }
        }
コード例 #16
0
    public void WriteScript(Menu menu, string namespaceName, string className, ClassQualifiers classQualifiers, string scriptPath, int menuPriority)
    {
        m_UsedNames = new HashSet <string>();

        MemoryStream memStream = BuildScript(menu, namespaceName, className, classQualifiers, menuPriority);

        string fullScriptPath = Path.Combine(Application.dataPath, scriptPath);

        EditorApplication.LockReloadAssemblies();
        try {
            try {
                using (FileStream fileStream = new FileStream(fullScriptPath, FileMode.Create, FileAccess.Write)) {
                    memStream.WriteTo(fileStream);
                    fileStream.Close();
                }
            } catch (Exception e) {
                Debug.LogError(e);
                throw;
            }
        } finally {
            EditorApplication.UnlockReloadAssemblies();
        }
        AssetDatabase.ImportAsset("Assets/Scripts/Util/Editor/ScenesMenu.cs");
    }
コード例 #17
0
        private static void Generate()
        {
            try
            {
                EditorApplication.LockReloadAssemblies();

                // Ensure that all dependencies are in place.
                if (DownloadCoreSdk.TryDownload() == DownloadResult.Error)
                {
                    return;
                }

                CopySchema();

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));

                var schemaCompilerPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, SchemaCompilerRelativePath));

                var workerJsonPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    // Ensure the schema compiler is executable.
                    var _ = RedirectedProcess.Run("chmod", "+x", schemaCompilerPath);
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var exitCode = RedirectedProcess.Run(Common.DotNetBinary,
                                                         ConstructArgs(projectPath, schemaCompilerPath, workerJsonPath));

                    if (exitCode != 0)
                    {
                        Debug.LogError("Failed to generate code.");
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #18
0
 public LockReloadAssembliesScope()
 {
     EditorApplication.LockReloadAssemblies();
 }
コード例 #19
0
        void OnGUI()
        {
            if (!initialized)
            {
                return;
            }

            var editorConfig      = ProjectFolders.Instance;
            var assetManageConfig = AssetManageConfig.Instance;

            var externalResourcesPath = editorConfig.ExternalResourcesPath;

            EditorGUILayout.Separator();

            var backgroundColor = new Color(0.3f, 0.3f, 0.5f);
            var labelColor      = new Color(0.8f, 0.8f, 0.8f, 0.8f);

            EditorLayoutTools.DrawLabelWithBackground("AssetInfoManifest", backgroundColor, labelColor);

            if (GUILayout.Button("Generate"))
            {
                // アセット情報ファイルを生成.
                AssetInfoManifestGenerator.Generate(externalResourcesPath, assetManageConfig);
            }

            GUILayout.Space(6f);

            EditorLayoutTools.DrawLabelWithBackground("ExternalResource", backgroundColor, labelColor);

            if (GUILayout.Button("Generate"))
            {
                if (ExternalResourceManager.BuildConfirm())
                {
                    var build = true;

                    #if ENABLE_CRIWARE_ADX || ENABLE_CRIWARE_SOFDEC
                    // CRIの最新アセットに更新.
                    CriAssetUpdater.Execute();
                    #endif

                    try
                    {
                        EditorApplication.LockReloadAssemblies();

                        // アセット情報ファイルを生成.
                        AssetInfoManifestGenerator.Generate(externalResourcesPath, assetManageConfig);

                        // 依存関係の検証.
                        var validate = AssetDependencies.Validate(externalResourcesPath);

                        if (!validate)
                        {
                            var messeage = "There is an incorrect reference.\nDo you want to cancel the build?";

                            if (!EditorUtility.DisplayDialog("InvalidDependant", messeage, "build", "cancel"))
                            {
                                build = false;

                                // ExternalResourceフォルダ以外の参照が含まれる場合は依存関係を表示.
                                InvalidDependantWindow.Open(externalResourcesPath);
                            }
                        }

                        // ビルド.
                        if (build)
                        {
                            ExternalResourceManager.Build(externalResourcesPath, assetManageConfig);
                        }
                    }
                    finally
                    {
                        EditorApplication.UnlockReloadAssemblies();
                    }
                }
            }

            EditorGUILayout.Separator();
        }
コード例 #20
0
        private static void PostReload()
        {
            EditorApplication.LockReloadAssemblies();

            try {
                Debug.Log("Verifying native libraries aren't loaded...");
                {
                    var processModules  = Process.GetCurrentProcess().Modules;
                    var nativePluginsId = new DirectoryInfo(IO.Utils.AGXUnityPluginDirectory);
                    foreach (ProcessModule processModule in processModules)
                    {
                        if (processModule.FileName.Contains(nativePluginsId.FullName))
                        {
                            throw new System.Exception($"AGX Dynamics module {processModule.ModuleName} is loaded. Unable to install new version of package.");
                        }
                    }
                }

                var packageName = string.Empty;
                foreach (var arg in System.Environment.GetCommandLineArgs())
                {
                    if (arg.StartsWith(s_packageIdentifier))
                    {
                        packageName = arg.Substring(s_packageIdentifier.Length);
                    }
                }

                if (string.IsNullOrEmpty(packageName))
                {
                    throw new System.Exception($"Unable to find package name identifier {s_packageIdentifier} in arguments list: " +
                                               string.Join(" ", System.Environment.GetEnvironmentVariables()));
                }

                Debug.Log("Removing old native binaries...");
                foreach (var nativePlugin in NativePlugins)
                {
                    var fi = new FileInfo(nativePlugin.assetPath);
                    Debug.Log($"    - {fi.Name}");
                    var fiMeta = new FileInfo(nativePlugin.assetPath + ".meta");
                    try {
                        fi.Delete();
                        if (fiMeta.Exists)
                        {
                            fiMeta.Delete();
                        }
                    }
                    catch (System.Exception) {
                        Debug.LogError("Fatal update error: Close Unity and remove AGX Dynamics for Unity directory and install the latest version.");
                        throw;
                    }
                }

                Debug.Log("Removing all non-user specific content...");
                IO.DirectoryContentHandler.DeleteContent();

                // This will generate compile errors from scripts using AGXUnity and
                // we don't know how to hide these until we're done, mainly because
                // we have no idea when we're done with the update.
                //
                // If this isn't performed, the compiler will throw exception due
                // to missing references and Unity will crash the first time we
                // use AGX Dynamics.
                AssetDatabase.Refresh();

                Debug.Log($"Starting import of package: {packageName}");
                AssetDatabase.ImportPackage(packageName, false);
            }
            catch (System.Exception e) {
                Debug.LogException(e);
            }

            Build.DefineSymbols.Remove(Build.DefineSymbols.ON_AGXUNITY_UPDATE);
            EditorApplication.UnlockReloadAssemblies();
        }
コード例 #21
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                EditorApplication.LockReloadAssemblies();

                var projectPath = Path.GetFullPath(Path.Combine(Common.GetThisPackagePath(),
                                                                CsProjectFile));


                // Fix up symlinking for Mac
                if (Application.platform == RuntimePlatform.OSXEditor)
                {
                    var packageAttributes = File.GetAttributes(Common.GetThisPackagePath());
                    if (packageAttributes.HasFlag(FileAttributes.ReparsePoint))
                    {
                        var process = RedirectedProcess.Command("pwd")
                                      .WithArgs("-P")
                                      .InDirectory(Common.GetThisPackagePath())
                                      .RedirectOutputOptions(OutputRedirectBehaviour.None);

                        var result   = process.RunAsync().Result;
                        var realPath = string.Join("\n", result.Stdout).Trim();

                        projectPath = Path.GetFullPath(Path.Combine(realPath, CsProjectFile));
                    }
                }

                var schemaCompilerPath = SchemaCompilerPath;

                var workerJsonPath =
                    Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    RedirectedProcess.Command("chmod")
                    .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                    .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                    .Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var errorMessage = new StringBuilder();
                    var exitCode     = RedirectedProcess.Command(Common.DotNetBinary)
                                       .WithArgs(ConstructArgs(projectPath, schemaCompilerPath, workerJsonPath))
                                       .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                       .AddErrorProcessing((line) => errorMessage.Append($"\n{line}"))
                                       .AddOutputProcessing(ProcessStdOut)
                                       .Run();

                    if (exitCode != 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError($"Error(s) compiling schema files!{errorMessage.ToString()}");
                            EditorApplication.delayCall += () =>
                            {
                                EditorUtility.DisplayDialog("Generate Code",
                                                            "Failed to generate code from schema.\nPlease view the console for errors.",
                                                            "Close");
                            };
                        }
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #22
0
    public bool Eval(List <LogEntry> logEntries, string code)
    {
        EditorApplication.LockReloadAssemblies();

        bool     status    = false;
        bool     hasOutput = false;
        object   output    = null;
        LogEntry cmdEntry  = null;

        string tmpCode = code.Trim();

        cmdEntry = new LogEntry()
        {
            logEntryType = LogEntryType.Command,
            command      = tmpCode
        };

        bool isExpression = false;

        try {
            if (tmpCode.StartsWith("="))
            {
                tmpCode      = "(" + tmpCode.Substring(1, tmpCode.Length - 1) + ");";
                isExpression = true;
            }
            Application.RegisterLogCallback(delegate(string cond, string sTrace, LogType lType) {
                cmdEntry.Add(new LogEntry()
                {
                    logEntryType   = LogEntryType.ConsoleLog,
                    condition      = cond,
                    stackTrace     = sTrace,
                    consoleLogType = lType
                });
            });
            status = Evaluator.Evaluate(tmpCode, out output, out hasOutput) == null;
            if (status)
            {
                logEntries.Add(cmdEntry);
            }
        } catch (Exception e) {
            cmdEntry.Add(new LogEntry()
            {
                logEntryType = LogEntryType.EvaluationError,
                error        = e.ToString().Trim() // TODO: Produce a stack trace a la Debug, and put it in stackTrace so we can filter it.
            });

            output    = new Evaluator.NoValueSet();
            hasOutput = false;
            status    = true; // Need this to avoid 'stickiness' where we let user
                              // continue editing due to incomplete code.
            logEntries.Add(cmdEntry);
        } finally {
            Application.RegisterLogCallback(null);
        }

        // Catch compile errors that are not dismissed as a product of interactive
        // editing by Mono.CSharp.Evaluator...
        StringBuilder buffer = FluffReporter();
        string        tmp    = buffer.ToString().Trim();

        buffer.Length = 0;
        if (!String.IsNullOrEmpty(tmp))
        {
            cmdEntry.Add(new LogEntry()
            {
                logEntryType = LogEntryType.SystemConsole,
                error        = tmp
            });
            status = false;
        }

        if (hasOutput && (isExpression || output is REPLMessage))
        {
            if (status)
            {
                outputBuffer.Length = 0;
                PrettyPrint.PP(outputBuffer, output);
                cmdEntry.Add(new LogEntry()
                {
                    logEntryType = LogEntryType.Output,
                    output       = outputBuffer.ToString().Trim()
                });
            }
        }

        EditorApplication.UnlockReloadAssemblies();
        return(status);
    }
コード例 #23
0
        void OnGUI()
        {
            if (!initialized)
            {
                return;
            }

            EditorGUILayout.Separator();

            EditorLayoutTools.Title("AssetInfoManifest");

            GUILayout.Space(2f);

            if (GUILayout.Button("Generate"))
            {
                // アセット情報ファイルを生成.
                AssetInfoManifestGenerator.Generate();
            }

            GUILayout.Space(6f);

            EditorLayoutTools.Title("ExternalResource");

            GUILayout.Space(2f);

            if (GUILayout.Button("Generate"))
            {
                if (BuildManager.BuildConfirm())
                {
                    var build = true;

                    #if ENABLE_CRIWARE_ADX || ENABLE_CRIWARE_SOFDEC
                    // CRIの最新アセットに更新.
                    CriAssetUpdater.Execute();
                    #endif

                    try
                    {
                        EditorApplication.LockReloadAssemblies();

                        // アセット情報ファイルを生成.
                        var assetInfoManifest = AssetInfoManifestGenerator.Generate();

                        // 依存関係の検証.
                        var validate = BuildManager.AssetDependenciesValidate(assetInfoManifest);

                        if (!validate)
                        {
                            var message = "There is an incorrect reference.\nDo you want to cancel the build?";

                            if (!EditorUtility.DisplayDialog("Invalid Dependencies", message, "build", "cancel"))
                            {
                                build = false;

                                // ExternalResourceフォルダ以外の参照が含まれる場合は依存関係を表示.
                                InvalidDependantWindow.Open();
                            }
                        }

                        // ビルド.
                        if (build)
                        {
                            var exportPath = BuildManager.GetExportPath();

                            if (!string.IsNullOrEmpty(exportPath))
                            {
                                if (onBuildStart != null)
                                {
                                    onBuildStart.OnNext(Unit.Default);
                                }

                                BuildManager.Build(exportPath, assetInfoManifest)
                                .ToObservable()
                                .Subscribe()
                                .AddTo(Disposable);
                            }
                            else
                            {
                                Debug.LogError("The export path is not set.");

                                var config = ManageConfig.Instance;

                                if (config != null)
                                {
                                    Selection.activeObject = config;
                                }
                            }
                        }
                    }
                    finally
                    {
                        EditorApplication.UnlockReloadAssemblies();
                    }
                }
            }

            EditorGUILayout.Separator();
        }
コード例 #24
0
        public void InstallPackage(PackageGroup group, string version)
        {
            if (EditorApplication.isCompiling)
            {
                return;
            }
            var package = group[version];

            var installSet = EnumerateDependencies(package).Where(dep => !dep.group.Installed).ToArray();
            var progress   = 0.01f;
            var stepSize   = 0.33f / installSet.Length;

            //Wait till all files are put in place to load new assemblies to make installation more consistent and faster
            EditorApplication.LockReloadAssemblies();
            try
            {
                EditorUtility.DisplayProgressBar("Creating Packages", $"{installSet.Length} packages", progress);
                foreach (var installable in installSet)
                {
                    //This will cause repeated installation of dependencies
                    string packageDirectory = installable.group.InstallDirectory;

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

                    EditorUtility.DisplayProgressBar("Creating Packages", $"Creating package.json for {installable.group.PackageName}", progress += stepSize / 2);
                    PackageHelper.GeneratePackageManifest(
                        installable.group.DependencyId.ToLower(), installable.group.InstallDirectory,
                        installable.group.PackageName, installable.group.Author,
                        installable.version,
                        installable.group.Description);
                }

                AssetDatabase.SaveAssets();
                try
                {
                    //Refresh here to update the AssetDatabase so that it can manage the creation of Manifests in the packages via the Unity Package path notation
                    //e.g Packages/com.passivepicasso.thunderkit/Editor
                    AssetDatabase.Refresh();
                }
                catch { }

                EditorUtility.DisplayProgressBar("Creating Package Manifests", $"Creating {installSet.Length} manifests", progress);
                foreach (var installable in installSet)
                {
                    var installableGroup = installable.group;
                    var manifestPath     = PathExtensions.Combine(installableGroup.PackageDirectory, $"{installableGroup.PackageName}.asset");
                    if (AssetDatabase.LoadAssetAtPath <Manifest>(manifestPath))
                    {
                        AssetDatabase.DeleteAsset(manifestPath);
                    }

                    EditorUtility.DisplayProgressBar("Creating Package Manifests", $"Creating manifest for {installable.group.PackageName}", progress += stepSize);

                    var manifest = ScriptableObject.CreateInstance <Manifest>();
                    AssetDatabase.CreateAsset(manifest, manifestPath);
                    PackageHelper.WriteAssetMetaData(manifestPath);
                    AssetDatabase.Refresh();

                    manifest = AssetDatabase.LoadAssetAtPath <Manifest>(manifestPath);
                    var identity = ScriptableObject.CreateInstance <ManifestIdentity>();
                    identity.name        = nameof(ManifestIdentity);
                    identity.Author      = installableGroup.Author;
                    identity.Description = installableGroup.Description;
                    identity.Name        = installableGroup.PackageName;
                    identity.Version     = version;
                    manifest.InsertElement(identity, 0);
                    manifest.Identity = identity;
                }
                //Refresh here to update the AssetDatabase's representation of the Assets with ThunderKit managed Meta files
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                EditorUtility.DisplayProgressBar("Defining Package Dependencies", $"Assigning dependencies for {installSet.Length} manifests", progress);
                foreach (var installable in installSet)
                {
                    var manifestPath        = PathExtensions.Combine(installable.group.PackageDirectory, $"{installable.group.PackageName}.asset");
                    var installableManifest = AssetDatabase.LoadAssetAtPath <Manifest>(manifestPath);
                    var identity            = installableManifest.Identity;
                    EditorUtility.DisplayProgressBar("Defining Package Dependencies", $"Assigning dependencies for {installable.group.PackageName}", progress);
                    identity.Dependencies = new Manifest[installable.dependencies.Length];
                    for (int i = 0; i < installable.dependencies.Length; i++)
                    {
                        var installableDependency = installable.dependencies[i];

                        EditorUtility.DisplayProgressBar("Defining Package Dependencies",
                                                         $"Assigning {installableDependency.group.PackageName} to {identity.Name}",
                                                         progress += stepSize / installable.dependencies.Length);

                        var manifestFileName        = $"{installableDependency.group.PackageName}.asset";
                        var dependencyAssetTempPath = PathExtensions.Combine(installableDependency.group.PackageDirectory, manifestFileName);
                        var manifest = AssetDatabase.LoadAssetAtPath <Manifest>(dependencyAssetTempPath);

                        if (!manifest)
                        {
                            var packageManifests = AssetDatabase.FindAssets($"t:{nameof(Manifest)}", new string[] { "Assets", "Packages" }).Select(x => AssetDatabase.GUIDToAssetPath(x)).ToArray();
                            manifest = packageManifests.Where(x => x.Contains(manifestFileName)).Select(x => AssetDatabase.LoadAssetAtPath <Manifest>(x)).FirstOrDefault();
                        }

                        identity.Dependencies[i] = manifest;
                    }
                    EditorUtility.SetDirty(installableManifest);
                    EditorUtility.SetDirty(identity);
                }

                EditorUtility.DisplayProgressBar("Installing Package Files", $"{installSet.Length} packages", progress);
                foreach (var installable in installSet)
                {
                    string packageDirectory = installable.group.InstallDirectory;

                    EditorUtility.DisplayProgressBar("Installing Package Files", $"Downloading {installable.group.PackageName}", progress += stepSize / 2);

                    installable.group.Source.OnInstallPackageFiles(installable, packageDirectory);

                    foreach (var assemblyPath in Directory.GetFiles(packageDirectory, "*.dll", SearchOption.AllDirectories))
                    {
                        PackageHelper.WriteAssemblyMetaData(assemblyPath, $"{assemblyPath}.meta");
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                AssetDatabase.SaveAssets();

                EditorApplication.update += OneRefresh;

                RefreshWait = EditorApplication.timeSinceStartup;
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #25
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                if (!File.Exists(CodegenExe))
                {
                    SetupProject();
                }

                EditorApplication.LockReloadAssemblies();

                Profiler.BeginSample("Add modules");
                UpdateModules();
                Profiler.EndSample();

                Profiler.BeginSample("Code generation");

                var schemaCompilerPath = SchemaCompilerPath;

                switch (Application.platform)
                {
                case RuntimePlatform.WindowsEditor:
                    schemaCompilerPath = Path.ChangeExtension(schemaCompilerPath, ".exe");
                    break;

                case RuntimePlatform.LinuxEditor:
                case RuntimePlatform.OSXEditor:
                    RedirectedProcess.Command("chmod")
                    .WithArgs("+x", $"\"{schemaCompilerPath}\"")
                    .InDirectory(Path.GetFullPath(Path.Combine(Application.dataPath, "..")))
                    .Run();
                    break;

                default:
                    throw new PlatformNotSupportedException(
                              $"The {Application.platform} platform does not support code generation.");
                }

                var workerJsonPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));

                using (new ShowProgressBarScope("Generating code..."))
                {
                    var errorMessage = new StringBuilder();
                    var exitCode     = RedirectedProcess.Command(Common.DotNetBinary)
                                       .WithArgs(ConstructArgs(CodegenExe, schemaCompilerPath, workerJsonPath))
                                       .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                       .AddErrorProcessing((line) => errorMessage.Append($"\n{line}"))
                                       .AddErrorProcessing(Debug.LogError)
                                       .AddOutputProcessing(ProcessStdOut)
                                       .Run();

                    if (exitCode.ExitCode != 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError($"Error(s) compiling schema files!{errorMessage}");
                            EditorApplication.delayCall += () =>
                            {
                                EditorUtility.DisplayDialog("Generate Code",
                                                            "Failed to generate code from schema.\nPlease view the console for errors.",
                                                            "Close");
                            };
                        }
                    }
                    else
                    {
                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Profiler.EndSample();
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #26
0
 public LockAssemblies()
 {
     EditorApplication.LockReloadAssemblies();
     IsDisposed = false;
 }
コード例 #27
0
        private static void Generate()
        {
            try
            {
                if (!Common.CheckDependencies())
                {
                    return;
                }

                if (!File.Exists(CodegenExe))
                {
                    SetupProject();
                }

                EditorApplication.LockReloadAssemblies();

                Profiler.BeginSample("Add modules");
                UpdateModules();
                Profiler.EndSample();

                Profiler.BeginSample("Code generation");

                using (new ShowProgressBarScope("Generating code..."))
                {
                    ResetCodegenLogCounter();

                    var toolsConfig      = GdkToolsConfiguration.GetOrCreateInstance();
                    var loggerOutputPath = toolsConfig.DefaultCodegenLogPath;

                    var exitCode = RedirectedProcess.Command(Common.DotNetBinary)
                                   .WithArgs("run", "-p", $"\"{CodegenExe}\"")
                                   .RedirectOutputOptions(OutputRedirectBehaviour.None)
                                   .AddOutputProcessing(ProcessDotnetOutput)
                                   .AddOutputProcessing(ProcessCodegenOutput)
                                   .Run();

                    var numWarnings = codegenLogCounts[CodegenLogLevel.Warn];
                    var numErrors   = codegenLogCounts[CodegenLogLevel.Error] + codegenLogCounts[CodegenLogLevel.Fatal];

                    if (exitCode.ExitCode != 0 || numErrors > 0)
                    {
                        if (!Application.isBatchMode)
                        {
                            Debug.LogError("Code generation failed! Please check the console for more information.");

                            EditorApplication.delayCall += () =>
                            {
                                if (File.Exists(loggerOutputPath))
                                {
                                    var option = EditorUtility.DisplayDialogComplex("Generate Code",
                                                                                    $"Code generation failed with {numWarnings} warnings and {numErrors} errors!{Environment.NewLine}{Environment.NewLine}"
                                                                                    + $"Please check the code generation logs for more information: {loggerOutputPath}",
                                                                                    "Open logfile",
                                                                                    "Close",
                                                                                    "");

                                    switch (option)
                                    {
                                    // Open logfile
                                    case 0:
                                        Application.OpenURL(loggerOutputPath);
                                        break;

                                    // Close
                                    case 1:
                                    // Alt
                                    case 2:
                                        break;

                                    default:
                                        throw new ArgumentOutOfRangeException(nameof(option), "Unrecognised option");
                                    }
                                }
                                else
                                {
                                    DisplayGeneralFailure();
                                }
                            };
                        }
                    }
                    else
                    {
                        if (numWarnings > 0)
                        {
                            Debug.LogWarning($"Code generation completed successfully with {numWarnings} warnings. Please check the logs for more information: {loggerOutputPath}");
                        }
                        else
                        {
                            Debug.Log("Code generation complete!");
                        }

                        File.WriteAllText(StartupCodegenMarkerFile, string.Empty);
                    }
                }

                AssetDatabase.Refresh();
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Profiler.EndSample();
                EditorApplication.UnlockReloadAssemblies();
            }
        }
コード例 #28
0
 private void LockReload()
 {
     EditorApplication.LockReloadAssemblies();
     _reimportLock = true;
 }
コード例 #29
0
        /// <summary>
        /// Compiles our generated code for the user
        /// </summary>
        public void Compile()
        {
            if (ActiveButton == null)
            {
                Debug.LogError("WHAT?! LOL");
                return;
            }

            if (string.IsNullOrEmpty(ActiveButton.ButtonName))
            {
                Debug.LogError("Can't have an empty class name");
                return;
            }

            EditorApplication.LockReloadAssemblies();

            int identity = 1;

            for (int i = 0; i < _editorButtons.Count; ++i)
            {
                if (_editorButtons[i].IsCreated)
                {
                    //Brand new class being added!
                    string networkObjectData   = SourceCodeNetworkObject(null, _editorButtons[i], identity);
                    string networkBehaviorData = SourceCodeNetworkBehavior(null, _editorButtons[i]);
                    if (!string.IsNullOrEmpty(networkObjectData))
                    {
                        using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, string.Format("{0}{1}.cs", _editorButtons[i].StrippedSearchName, "NetworkObject"))))
                        {
                            sw.Write(networkObjectData);
                        }

                        using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, string.Format("{0}{1}.cs", _editorButtons[i].StrippedSearchName, "Behavior"))))
                        {
                            sw.Write(networkBehaviorData);
                        }
                        identity++;

                        string strippedName = _editorButtons[i].StrippedSearchName;
                        _editorButtons[i].ButtonName = strippedName + "NetworkObject";
                    }
                }
                else
                {
                    if (_editorButtons[i].TiedObject != null)
                    {
                        if (_editorButtons[i].TiedObject.IsNetworkBehavior)
                        {
                            string networkBehaviorData = SourceCodeNetworkBehavior(null, _editorButtons[i]);

                            using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, _editorButtons[i].TiedObject.Filename)))
                            {
                                sw.Write(networkBehaviorData);
                            }
                        }
                        else if (_editorButtons[i].TiedObject.IsNetworkObject)
                        {
                            string networkObjectData = SourceCodeNetworkObject(null, _editorButtons[i], identity);
                            using (StreamWriter sw = File.CreateText(Path.Combine(_userStoringPath, _editorButtons[i].TiedObject.Filename)))
                            {
                                sw.Write(networkObjectData);
                            }
                            identity++;
                        }
                    }
                }
            }

            string factoryData = SourceCodeFactory();

            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkObjectFactory.cs")))
            {
                sw.Write(factoryData);
            }

            string networkManagerData = SourceCodeNetworkManager();

            using (StreamWriter sw = File.CreateText(Path.Combine(_storingPath, "NetworkManager.cs")))
            {
                sw.Write(networkManagerData);
            }

            //IFormatter previousSavedState = new BinaryFormatter();
            //using (Stream s = new FileStream(Path.Combine(Application.persistentDataPath, FN_WIZARD_DATA), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            //{
            //    previousSavedState.Serialize(s, _editorButtons);
            //}

            EditorApplication.UnlockReloadAssemblies();

            AssetDatabase.Refresh();

            //_editorButtons.Remove(ActiveButton);
            ActiveButton = null;
            CloseFinal();
        }
コード例 #30
0
        /// <summary>
        /// 右側のツールバー
        /// </summary>
        static void OnRightToolbarGUI()
        {
            //if( E.i.enabled ) return;
            if (s_styles == null)
            {
                s_styles = new Styles();
            }

            ScopeChange.Begin();
            m_lockReloadAssemblies = GUILayout.Toggle(m_lockReloadAssemblies, EditorIcon.assemblylock, s_styles.Button, GUILayout.Width(s_styles.IconButtonSize));
            if (ScopeChange.End())
            {
                if (m_lockReloadAssemblies)
                {
                    EditorApplication.LockReloadAssemblies();
                    EditorHelper.ShowMessagePop("Lock Reload Assemblies");
                }
                else
                {
                    EditorApplication.UnlockReloadAssemblies();
                    AssetDatabase.Refresh();
                    EditorHelper.ShowMessagePop("Unlock Reload Assemblies");
                }
            }

            if (UnitySymbol.UNITY_2019_3_OR_NEWER)
            {
                ScopeChange.Begin();
                var cont   = EditorHelper.TempContent("PlayMode", UnityEditorEditorSettings.enterPlayModeOptionsEnabled ? EditorIcon.lightmeter_greenlight : EditorIcon.lightmeter_lightrim);
                var toggle = GUILayout.Toggle(UnityEditorEditorSettings.enterPlayModeOptionsEnabled, cont, s_styles.Button2, GUILayout.Width(cont.CalcWidth_label() - 16));
                if (ScopeChange.End())
                {
                    UnityEditorEditorSettings.enterPlayModeOptionsEnabled = toggle;
                }
            }



            if (UnitySymbol.UNITY_2019_3_OR_NEWER)
            {
            }
            else
            {
                GUILayout.BeginVertical();
                GUILayout.Space(2);
                GUILayout.BeginHorizontal();
            }

            Button_OpenCSProject();

            GUILayout.Space(SPACE);

            Button_ScreenShot();

            GUILayout.Space(SPACE);

            Button_AssetStore();

            //Button_Avs();
#if UNITY_2019_3_OR_NEWER
            var renderPipelineAsset = UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline;
#else
            var renderPipelineAsset = UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset;
#endif
            //Button_RenderPipe();

            if (renderPipelineAsset == null)
            {
                LabelBox("Built-in RP");
            }
            else
            {
                var rpType = renderPipelineAsset.GetType();

                if (rpType == UnityTypes.UnityEngine_Rendering_Universal_UniversalRenderPipelineAsset)
                {
                    LabelBox("URP");
                }
                else if (rpType == UnityTypes.UnityEngine_Rendering_HighDefinition_HDRenderPipelineAsset)
                {
                    LabelBox("HDRP");
                }
                else
                {
                    LabelBox("Custom RP");
                }
                //	GUILayout.Label( UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline.GetTypeName() );
                //Debug.Log( UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline.GetType().AssemblyQualifiedName );
            }

            GUILayout.FlexibleSpace();

            if (GUILayout.Button(EditorHelper.TempContent(Icon.Get("Unity Hub")), s_styles.Button, GUILayout.Width(s_styles.IconButtonSize)))
            {
                Help.BrowseURL("unityhub://");
            }

            if (UnitySymbol.UNITY_2019_3_OR_NEWER)
            {
            }
            else
            {
                GUILayout.EndHorizontal();
                GUILayout.Space(2);
                GUILayout.EndVertical();
            }
        }