Ejemplo n.º 1
0
        // Deletes the assets of the instance IDs, with an optional user confirmation dialog.
        // Returns true if the delete operation was successfully performed on all assets.
        // Note: Zero input assets always returns true.
        // Also note that the operation cannot be undone even if some operations failed.
        internal static bool DeleteAssets(List <int> instanceIDs, bool askIfSure)
        {
            if (instanceIDs.Count == 0)
            {
                return(true);
            }

            bool foundAssetsFolder = instanceIDs.IndexOf(AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets")) >= 0;

            if (foundAssetsFolder)
            {
                EditorUtility.DisplayDialog(L10n.Tr("Cannot Delete"), L10n.Tr("Deleting the 'Assets' folder is not allowed"), L10n.Tr("Ok"));
                return(false);
            }

            var paths = GetMainPathsOfAssets(instanceIDs).ToList();

            if (paths.Count == 0)
            {
                return(false);
            }

            if (askIfSure)
            {
                string title;
                if (paths.Count > 1)
                {
                    title = L10n.Tr("Delete selected assets?");
                }
                else
                {
                    title = L10n.Tr("Delete selected asset?");
                }

                int maxCount = 3;
                var infotext = new StringBuilder();
                for (int i = 0; i < paths.Count && i < maxCount; ++i)
                {
                    infotext.AppendLine("   " + paths[i]);
                }
                if (paths.Count > maxCount)
                {
                    infotext.AppendLine("   ...");
                }
                infotext.AppendLine(L10n.Tr("You cannot undo this action."));
                if (!EditorUtility.DisplayDialog(title, infotext.ToString(), L10n.Tr("Delete"), L10n.Tr("Cancel")))
                {
                    return(false);
                }
            }

            bool success = true;

            AssetDatabase.StartAssetEditing();
            foreach (string path in paths)
            {
                if (!AssetDatabase.MoveAssetToTrash(path))
                {
                    success = false;
                }
            }
            AssetDatabase.StopAssetEditing();
            if (!success)
            {
                string message = (Provider.enabled && Provider.onlineState == OnlineState.Offline) ?
                                 L10n.Tr("Some assets could not be deleted.\nMake sure you are connected to your Version Control server or \"Work Offline\" is enabled.") :
                                 L10n.Tr("Some assets could not be deleted.\nMake sure nothing is keeping a hook on them, like a loaded DLL for example.");

                EditorUtility.DisplayDialog(L10n.Tr("Cannot Delete"), message, L10n.Tr("Ok"));
            }
            return(success);
        }
Ejemplo n.º 2
0
        void AnimationClipGUI()
        {
            string errors           = m_AnimationImportErrors.stringValue;
            string warnings         = m_AnimationImportWarnings.stringValue;
            string rigWarnings      = m_RigImportWarnings.stringValue;
            string retargetWarnings = m_AnimationRetargetingWarnings.stringValue;

            if (errors.Length > 0)
            {
                EditorGUILayout.HelpBox(styles.ErrorsFoundWhileImportingThisAnimation);
            }
            else
            {
                if (rigWarnings.Length > 0)
                {
                    EditorGUILayout.HelpBox(styles.WarningsFoundWhileImportingRig);
                }

                if (warnings.Length > 0)
                {
                    EditorGUILayout.HelpBox(styles.WarningsFoundWhileImportingThisAnimation);
                }
            }

            // Show general animation import settings
            AnimationSettings();

            if (serializedObject.isEditingMultipleObjects)
            {
                return;
            }

            Profiler.BeginSample("Clip inspector");

            EditorGUILayout.Space();

            // Show list of animations and inspector for individual animation
            if (targets.Length == 1)
            {
                AnimationSplitTable();
            }
            else
            {
                GUILayout.Label(styles.clipMultiEditInfo, EditorStyles.helpBox);
            }

            Profiler.EndSample();

            RootMotionNodeSettings();

            importMessageFoldout = EditorGUILayout.Foldout(importMessageFoldout, styles.ImportMessages, true);

            if (importMessageFoldout)
            {
                if (errors.Length > 0)
                {
                    EditorGUILayout.HelpBox(L10n.Tr(errors), MessageType.Error);
                }
                if (warnings.Length > 0)
                {
                    EditorGUILayout.HelpBox(L10n.Tr(warnings), MessageType.Warning);
                }
                if (animationType == ModelImporterAnimationType.Human)
                {
                    EditorGUILayout.PropertyField(m_AnimationDoRetargetingWarnings, styles.GenerateRetargetingWarnings);

                    if (m_AnimationDoRetargetingWarnings.boolValue)
                    {
                        if (retargetWarnings.Length > 0)
                        {
                            EditorGUILayout.HelpBox(L10n.Tr(retargetWarnings), MessageType.Info);
                        }
                    }
                    else
                    {
                        EditorGUILayout.HelpBox(styles.RetargetingQualityCompares);
                    }
                }
            }
        }
        private void ReadPreferences()
        {
            m_ScriptEditorPath.str = CodeEditor.Editor.EditorInstallation.Path;

            m_ExternalEditorSupportsUnityProj = EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false);
            m_ImageAppPath.str = EditorPrefs.GetString("kImagesDefaultApp");

            m_ScriptApps         = BuildAppPathList(m_ScriptEditorPath, kRecentScriptAppsKey, "internal");
            m_ScriptAppsEditions = new string[m_ScriptApps.Length];

            var foundScriptEditorPaths = CodeEditor.Editor.GetFoundScriptEditorPaths();

            foreach (var scriptEditorPath in foundScriptEditorPaths.Keys)
            {
                ArrayUtility.Add(ref m_ScriptApps, scriptEditorPath);
                ArrayUtility.Add(ref m_ScriptAppsEditions, null);
            }

            m_ImageApps = BuildAppPathList(m_ImageAppPath, kRecentImageAppsKey, "");

            m_ScriptAppDisplayNames = BuildFriendlyAppNameList(m_ScriptApps, m_ScriptAppsEditions, foundScriptEditorPaths,
                                                               "Open by file extension");

            m_ImageAppDisplayNames = BuildFriendlyAppNameList(m_ImageApps, null, null,
                                                              L10n.Tr("Open by file extension"));

            m_DiffTools = InternalEditorUtility.GetAvailableDiffTools();

            // only show warning if has team license
            if ((m_DiffTools == null || m_DiffTools.Length == 0) && InternalEditorUtility.HasTeamLicense())
            {
                m_noDiffToolsMessage = InternalEditorUtility.GetNoDiffToolsDetectedMessage();
            }

            string diffTool = EditorPrefs.GetString("kDiffsDefaultApp");

            m_DiffToolIndex = ArrayUtility.IndexOf(m_DiffTools, diffTool);
            if (m_DiffToolIndex == -1)
            {
                m_DiffToolIndex = 0;
            }

            m_AutoRefresh = EditorPrefs.GetBool("kAutoRefresh");

            m_ReopenLastUsedProjectOnStartup = EditorPrefs.GetBool("ReopenLastUsedProjectOnStartup");

            m_UseOSColorPicker            = EditorPrefs.GetBool("UseOSColorPicker");
            m_EnableEditorAnalytics       = EditorPrefs.GetBool("EnableEditorAnalytics", true);
            m_ShowAssetStoreSearchHits    = EditorPrefs.GetBool("ShowAssetStoreSearchHits", true);
            m_VerifySavingAssets          = EditorPrefs.GetBool("VerifySavingAssets", false);
            m_ScriptCompilationDuringPlay = (ScriptChangesDuringPlayOptions)EditorPrefs.GetInt("ScriptCompilationDuringPlay", 0);
            m_DeveloperMode = Unsupported.IsDeveloperMode();

            m_GICacheSettings.m_EnableCustomPath = EditorPrefs.GetBool("GICacheEnableCustomPath");
            m_GICacheSettings.m_CachePath        = EditorPrefs.GetString("GICacheFolder");
            m_GICacheSettings.m_MaximumSize      = EditorPrefs.GetInt("GICacheMaximumSizeGB", 10);
            m_GICacheSettings.m_CompressionLevel = EditorPrefs.GetInt("GICacheCompressionLevel");

            m_SpriteAtlasCacheSize = EditorPrefs.GetInt("SpritePackerCacheMaximumSizeGB");

            m_AllowAttachedDebuggingOfEditor = EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true);
            m_EnableEditorLocalization       = EditorPrefs.GetBool("Editor.kEnableEditorLocalization", true);
            m_SelectedLanguage           = EditorPrefs.GetString("Editor.kEditorLocale", LocalizationDatabase.GetDefaultEditorLanguage().ToString());
            m_AllowAlphaNumericHierarchy = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false);
            m_EnableCodeCoverage         = EditorPrefs.GetBool("CodeCoverageEnabled", false);

            m_CompressAssetsOnImport = Unsupported.GetApplicationSettingCompressAssetsOnImport();
            m_GpuDevice = EditorPrefs.GetString("GpuDeviceName");

            foreach (IPreferenceWindowExtension extension in prefWinExtensions)
            {
                extension.ReadPreferences();
            }
        }
        void ShowBuildTargetSettings()
        {
            EditorGUIUtility.labelWidth = Mathf.Min(180, (position.width - 265) * 0.47f);

            BuildTarget      buildTarget      = EditorUserBuildSettingsUtils.CalculateSelectedBuildTarget();
            BuildTargetGroup buildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup;
            BuildPlatform    platform         = BuildPlatforms.instance.BuildPlatformFromTargetGroup(buildTargetGroup);
            bool             licensed         = BuildPipeline.LicenseCheck(buildTarget);

            // Draw the group name
            GUILayout.Space(18);

            // Draw icon and text of title separately so we can control the space between them
            Rect r = GUILayoutUtility.GetRect(50, 36);

            r.x += 1;
            GUI.Label(new Rect(r.x + 3, r.y + 3, 32, 32), platform.title.image, GUIStyle.none);
            GUI.Toggle(r, false, platform.title.text, styles.platformSelector);

            GUILayout.Space(10);

            if (platform.targetGroup == BuildTargetGroup.WebGL && !BuildPipeline.IsBuildTargetSupported(platform.targetGroup, buildTarget))
            {
                if (IntPtr.Size == 4)
                {
                    GUILayout.Label("Building for WebGL requires a 64-bit Unity editor.");
                    GUIBuildButtons(false, false, false, platform);
                    return;
                }
            }

            string moduleName = Modules.ModuleManager.GetTargetStringFrom(buildTargetGroup, buildTarget);

            if (IsModuleNotInstalled(buildTargetGroup, buildTarget))
            {
                GUILayout.Label(EditorGUIUtility.TextContent(string.Format(styles.noModuleLoaded, BuildPlatforms.instance.GetModuleDisplayName(buildTargetGroup, buildTarget))));
                if (GUILayout.Button(styles.openDownloadPage, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
                {
                    string url = GetPlaybackEngineDownloadURL(moduleName);
                    Help.BrowseURL(url);
                }
                GUIBuildButtons(false, false, false, platform);
                return;
            }
            else if (Application.HasProLicense() && !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(buildTarget))
            {
                // Show copy for using personal edition build targets with pro edition editor
                string infoText = string.Format(styles.infoText,
                                                BuildPlatforms.instance.GetBuildTargetDisplayName(buildTargetGroup, buildTarget));

                GUILayout.BeginVertical(EditorStyles.helpBox);
                GUILayout.Label(infoText, EditorStyles.wordWrappedMiniLabel);
                GUILayout.BeginHorizontal();
                if (GUILayout.Button(styles.eula, EditorStyles.miniButton))
                {
                    Application.OpenURL("http://unity3d.com/legal/eula");
                }
                if (GUILayout.Button(string.Format(styles.addToYourPro, BuildPlatforms.instance.GetBuildTargetDisplayName(buildTargetGroup, buildTarget)), EditorStyles.miniButton))
                {
                    Application.OpenURL("http://unity3d.com/get-unity");
                }
                GUILayout.EndHorizontal();
                GUILayout.EndVertical();
            }

            GUIContent error = styles.GetDownloadErrorForTarget(buildTarget);

            if (error != null)
            {
                GUILayout.Label(error, EditorStyles.wordWrappedLabel);
                GUIBuildButtons(false, false, false, platform);
                return;
            }

            // Draw not licensed buy now UI
            if (!licensed)
            {
                string niceName   = BuildPipeline.GetBuildTargetGroupDisplayName(buildTargetGroup);
                string licenseMsg = "Your license does not cover {0} Publishing.";
                string buttonMsg  = "Go to Our Online Store";
                if (BuildTargetDiscovery.PlatformHasFlag(buildTarget, TargetAttributes.IsConsole))
                {
                    licenseMsg += "Please see the {0} section of the Platform Module Installation documentation for more details.";
                    buttonMsg   = "Platform Module Installation";
                }
                else if (BuildTargetDiscovery.PlatformHasFlag(buildTarget, TargetAttributes.IsStandalonePlatform))
                {
                    buttonMsg = "";
                }

                GUIContent[] notLicensedMessage =
                {
                    EditorGUIUtility.TextContent(string.Format(L10n.Tr(licenseMsg), niceName)),
                    EditorGUIUtility.TextContent(L10n.Tr(buttonMsg)),
                    new GUIContent(styles.shopURL)
                };

                GUILayout.Label(notLicensedMessage[0], EditorStyles.wordWrappedLabel);
                GUILayout.Space(5);
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (notLicensedMessage[1].text.Length != 0)
                {
                    if (GUILayout.Button(notLicensedMessage[1]))
                    {
                        Application.OpenURL(notLicensedMessage[2].text);
                    }
                }
                GUILayout.EndHorizontal();
                GUIBuildButtons(false, false, false, platform);
                return;
            }

            // FIXME: WHY IS THIS ALL IN ONE FUNCTION?!
            // Draw the side bar to the right. Different options like specific Standalone player to build, profiling and debugging options, etc.
            string module = ModuleManager.GetTargetStringFrom(platform.targetGroup, buildTarget);
            IBuildWindowExtension buildWindowExtension = ModuleManager.GetBuildWindowExtension(module);

            if (buildWindowExtension != null)
            {
                buildWindowExtension.ShowPlatformBuildOptions();
            }

            GUI.changed = false;
            GUI.enabled = true;

            bool enableBuildButton = buildWindowExtension != null?buildWindowExtension.EnabledBuildButton() : true;

            bool enableBuildAndRunButton = false;

            bool shouldDrawDebuggingToggle = buildWindowExtension != null?buildWindowExtension.ShouldDrawScriptDebuggingCheckbox() : true;

            bool shouldDrawExplicitNullChecksToggle = buildWindowExtension != null?buildWindowExtension.ShouldDrawExplicitNullCheckbox() : false;

            bool shouldDrawDivideByZeroChecksToggle = buildWindowExtension != null?buildWindowExtension.ShouldDrawExplicitDivideByZeroCheckbox() : false;

            bool shouldDrawArrayBoundsChecksToggle = buildWindowExtension != null?buildWindowExtension.ShouldDrawExplicitArrayBoundsCheckbox() : false;

            bool shouldDrawDevelopmentPlayerToggle = buildWindowExtension != null?buildWindowExtension.ShouldDrawDevelopmentPlayerCheckbox() : true;

            IBuildPostprocessor postprocessor = ModuleManager.GetBuildPostProcessor(buildTargetGroup, buildTarget);
            bool enableBuildScriptsOnly       = (postprocessor != null ? postprocessor.SupportsScriptsOnlyBuild() : false);
            bool canInstallInBuildFolder      = false;

            if (BuildPipeline.IsBuildTargetSupported(buildTargetGroup, buildTarget))
            {
                bool shouldDrawProfilerToggles = buildWindowExtension != null?buildWindowExtension.ShouldDrawProfilerCheckbox() : true;

                GUI.enabled = shouldDrawDevelopmentPlayerToggle;
                if (shouldDrawDevelopmentPlayerToggle)
                {
                    EditorUserBuildSettings.development = EditorGUILayout.Toggle(styles.debugBuild, EditorUserBuildSettings.development);
                }

                bool developmentBuild = EditorUserBuildSettings.development;

                GUI.enabled = developmentBuild;

                if (shouldDrawProfilerToggles)
                {
                    var profilerDisabled = !GUI.enabled && !developmentBuild;

                    var autoConnectLabel = profilerDisabled ? styles.autoconnectProfilerDisabled : styles.autoconnectProfiler;
                    EditorUserBuildSettings.connectProfiler = EditorGUILayout.Toggle(autoConnectLabel, EditorUserBuildSettings.connectProfiler);

                    var buildWithDeepProfilerLabel = profilerDisabled ? styles.buildWithDeepProfilerDisabled : styles.buildWithDeepProfiler;
                    EditorUserBuildSettings.buildWithDeepProfilingSupport = EditorGUILayout.Toggle(buildWithDeepProfilerLabel, EditorUserBuildSettings.buildWithDeepProfilingSupport);
                }

                GUI.enabled = developmentBuild;
                if (shouldDrawDebuggingToggle)
                {
                    using (new EditorGUI.DisabledScope(buildWindowExtension != null ? buildWindowExtension.ShouldDisableManagedDebuggerCheckboxes() : false))
                    {
                        EditorUserBuildSettings.allowDebugging = EditorGUILayout.Toggle(styles.allowDebugging, EditorUserBuildSettings.allowDebugging);

                        // Not all platforms have native dialog implemented in Runtime\Misc\GiveDebuggerChanceToAttachIfRequired.cpp
                        // Display this option only for developer builds
                        bool shouldDrawWaitForManagedDebugger = buildWindowExtension != null?buildWindowExtension.ShouldDrawWaitForManagedDebugger() : false;

                        if (EditorUserBuildSettings.allowDebugging && shouldDrawWaitForManagedDebugger)
                        {
                            EditorUserBuildSettings.waitForManagedDebugger = EditorGUILayout.Toggle(styles.waitForManagedDebugger, EditorUserBuildSettings.waitForManagedDebugger);
                        }
                    }

                    if (EditorUserBuildSettings.allowDebugging && PlayerSettings.GetScriptingBackend(buildTargetGroup) == ScriptingImplementation.IL2CPP)
                    {
                        var  apiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(buildTargetGroup);
                        bool isDebuggerUsable      = apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0;

                        if (!isDebuggerUsable)
                        {
                            EditorGUILayout.HelpBox("Script debugging is only supported with IL2CPP on .NET 4.x and .NET Standard 2.0 API Compatibility Levels.", MessageType.Warning);
                        }
                    }
                }


                if (shouldDrawExplicitNullChecksToggle)
                {
                    // Force 'ExplicitNullChecks' to true if it's a development build.
                    GUI.enabled = !developmentBuild;
                    if (GUI.enabled == false)
                    {
                        EditorUserBuildSettings.explicitNullChecks = true;
                    }
                    EditorUserBuildSettings.explicitNullChecks = EditorGUILayout.Toggle(styles.explicitNullChecks, EditorUserBuildSettings.explicitNullChecks);
                    // Undo force from above
                    GUI.enabled = developmentBuild;
                }

                if (shouldDrawDivideByZeroChecksToggle)
                {
                    // Force 'explicitDivideByZeroChecks' to true if it's a development build.
                    GUI.enabled = !developmentBuild;
                    if (GUI.enabled == false)
                    {
                        EditorUserBuildSettings.explicitDivideByZeroChecks = true;
                    }
                    EditorUserBuildSettings.explicitDivideByZeroChecks = EditorGUILayout.Toggle(styles.explicitDivideByZeroChecks, EditorUserBuildSettings.explicitDivideByZeroChecks);
                    // Undo force from above
                    GUI.enabled = developmentBuild;
                }

                if (shouldDrawArrayBoundsChecksToggle)
                {
                    // Force 'explicitArrayBoundsChecks' to true if it's a development build.
                    GUI.enabled = !developmentBuild;
                    if (GUI.enabled == false)
                    {
                        EditorUserBuildSettings.explicitArrayBoundsChecks = true;
                    }
                    EditorUserBuildSettings.explicitArrayBoundsChecks = EditorGUILayout.Toggle(styles.explicitArrayBoundsChecks, EditorUserBuildSettings.explicitArrayBoundsChecks);
                    // Undo force from above
                    GUI.enabled = developmentBuild;
                }

                if (buildWindowExtension != null && enableBuildScriptsOnly)
                {
                    buildWindowExtension.DoScriptsOnlyGUI();
                }

                GUI.enabled = true;

                GUILayout.FlexibleSpace();

                if (postprocessor != null && postprocessor.SupportsLz4Compression())
                {
                    var cmpIdx = Array.IndexOf(styles.compressionTypes, EditorUserBuildSettings.GetCompressionType(buildTargetGroup));
                    if (cmpIdx == -1)
                    {
                        cmpIdx = Array.IndexOf(styles.compressionTypes, postprocessor.GetDefaultCompression());
                    }
                    if (cmpIdx == -1)
                    {
                        cmpIdx = 1; // Lz4 by default.
                    }
                    cmpIdx = EditorGUILayout.Popup(styles.compressionMethod, cmpIdx, styles.compressionStrings);
                    EditorUserBuildSettings.SetCompressionType(buildTargetGroup, styles.compressionTypes[cmpIdx]);
                }

                canInstallInBuildFolder = Unsupported.IsSourceBuild() && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTargetGroup, buildTarget);

                if (enableBuildButton)
                {
                    enableBuildAndRunButton = buildWindowExtension != null?buildWindowExtension.EnabledBuildAndRunButton() &&
                                              !(EditorUserBuildSettings.installInBuildFolder) : !(EditorUserBuildSettings.installInBuildFolder);
                }
            }
            else
            {
                GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));

                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));

                GUILayout.Label(string.Format(L10n.Tr("{0} is not supported in this build.\nDownload a build that supports it."), BuildPipeline.GetBuildTargetGroupDisplayName(buildTargetGroup)));

                GUILayout.EndVertical();
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }

            GUIBuildButtons(buildWindowExtension, enableBuildButton, enableBuildAndRunButton,
                            canInstallInBuildFolder, platform);
        }
Ejemplo n.º 5
0
        // Internal for testing framework
        internal void SaveDirtyPrefabAssets()
        {
            if (assetTargets == null)
            {
                return;
            }

            if (assetTarget == null)
            {
                return;
            }

            m_DirtyPrefabAssets.Clear();
            foreach (var asset in assetTargets)
            {
                // The asset could have been deleted when this method is called from OnDestroy().
                // E.g delete the selected prefab asset from the Project Browser.
                if (asset == null)
                {
                    continue;
                }

                if (!EditorUtility.IsPersistent(asset))
                {
                    continue;
                }

                if (!(asset is GameObject))
                {
                    continue;
                }

                var rootGameObject = (GameObject)asset;
                if (IsDirty(rootGameObject))
                {
                    m_DirtyPrefabAssets.Add(rootGameObject);
                }
            }

            if (m_DirtyPrefabAssets.Count > 0)
            {
                bool savedPrefab = false;
                AssetDatabase.StartAssetEditing();
                try
                {
                    foreach (var rootGameObject in m_DirtyPrefabAssets)
                    {
                        bool savedSuccesfully;
                        PrefabUtility.SavePrefabAsset(rootGameObject, out savedSuccesfully);
                        if (!savedSuccesfully)
                        {
                            string title   = L10n.Tr("Saving Failed");
                            string message = L10n.Tr("Check the Console window to get more insight into what needs to be fixed on the Prefab Asset.\n\nYou can open Prefab Mode to fix any issues on child GameObjects");
                            EditorUtility.DisplayDialog(title, message, L10n.Tr("OK"));

                            m_SavingHasFailed = true;
                            break;
                        }

                        savedPrefab |= savedSuccesfully;
                    }
                }
                finally
                {
                    AssetDatabase.StopAssetEditing();

                    // All inspectors needs to be rebuild to ensure property changes are reflected after saving the Prefab shown.
                    // (Saving clears the m_DirtyIndex of the target which is used for updating inspectors via SerializedObject::UpdateIfRequiredOrScript()
                    // and thus the cached dirty index in SerializedObject is not updated meaning the source object is not reloaded even though it changed)
                    if (savedPrefab)
                    {
                        EditorUtility.ForceRebuildInspectors();
                    }
                }
            }
        }
        private bool ExtractMaterialsGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Materials);
                using (new EditorGUI.DisabledScope(!m_CanExtractEmbeddedMaterials))
                {
                    if (GUILayout.Button(Styles.ExtractEmbeddedMaterials))
                    {
                        // use the first target for selecting the destination folder, but apply that path for all targets
                        string destinationPath = (target as ModelImporter).assetPath;
                        destinationPath = EditorUtility.SaveFolderPanel("Select Materials Folder",
                                                                        FileUtil.DeleteLastPathNameComponent(destinationPath), "");
                        if (string.IsNullOrEmpty(destinationPath))
                        {
                            // cancel the extraction if the user did not select a folder
                            return(false);
                        }

                        string assetPath = FileUtil.GetProjectRelativePath(destinationPath);

                        //Where all the required embedded materials are not in the asset database, we need to reimport them
                        if (!AllEmbeddedMaterialsAreImported())
                        {
                            if (EditorUtility.DisplayDialog(L10n.Tr("Are you sure you want to re-extract the Materials?"), L10n.Tr("In order to re-extract the Materials we'll need to reimport the mesh, this might take a while. Do you want to continue?"), L10n.Tr("Yes"), L10n.Tr("No")))
                            {
                                ReimportEmbeddedMaterials();
                            }
                            else
                            {
                                return(false);
                            }
                        }

                        if (!assetPath.StartsWith("Assets"))
                        {
                            destinationPath = FileUtil.NiceWinPath(destinationPath);
                            // Destination could be a package. Need to get assetPath instead of relativePath
                            // The GUID isn't known yet so can't find it from that
                            foreach (var package in PackageManager.PackageInfo.GetAllRegisteredPackages())
                            {
                                if (destinationPath.StartsWith(package.resolvedPath))
                                {
                                    assetPath = package.assetPath + destinationPath.Substring(package.resolvedPath.Length);
                                    break;
                                }
                            }
                        }

                        if (string.IsNullOrEmpty(assetPath))
                        {
                            return(false);
                        }

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();
                            PrefabUtility.ExtractMaterialsFromAsset(targets, assetPath);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

                        // AssetDatabase.StopAssetEditing() invokes OnEnable(), which invalidates all the serialized properties, so we must return.
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 7
0
        // Deletes the assets of the instance IDs, with an optional user confirmation dialog.
        // Returns true if the delete operation was successfully performed on all assets.
        // Note: Zero input assets always returns true.
        // Also note that the operation cannot be undone even if some operations failed.
        internal static bool DeleteAssets(List <int> instanceIDs, bool askIfSure)
        {
            if (instanceIDs.Count == 0)
            {
                return(true);
            }

            bool foundAssetsFolder = instanceIDs.IndexOf(AssetDatabase.GetMainAssetOrInProgressProxyInstanceID("Assets")) >= 0;

            if (foundAssetsFolder)
            {
                EditorUtility.DisplayDialog(L10n.Tr("Cannot Delete"), L10n.Tr("Deleting the 'Assets' folder is not allowed"), L10n.Tr("Ok"));
                return(false);
            }

            bool reparentMaterials = false;
            var  paths             = GetMainPathsOfAssets(instanceIDs).ToArray();

            if (paths.Length == 0)
            {
                return(false);
            }

            if (askIfSure)
            {
                string title;
                if (paths.Length > 1)
                {
                    title = L10n.Tr("Delete selected assets?");
                }
                else
                {
                    title = L10n.Tr("Delete selected asset?");
                }

                int  maxCount         = 3;
                bool containsMaterial = false;

                var infotext = new StringBuilder();
                for (int i = 0; i < paths.Length; ++i)
                {
                    if (i < maxCount)
                    {
                        infotext.AppendLine(paths[i]);
                    }

                    if (paths[i].EndsWith(".mat", StringComparison.OrdinalIgnoreCase))
                    {
                        containsMaterial = true;
                        if (i >= maxCount)
                        {
                            break;
                        }
                    }
                }

                if (paths.Length > maxCount)
                {
                    infotext.AppendLine("...");
                }
                infotext.AppendLine("");
                infotext.AppendLine(L10n.Tr("You cannot undo the delete assets action."));

                containsMaterial &= AnyTargetMaterialHasChildren(paths);
                if (containsMaterial)
                {
                    infotext.AppendLine();
                    string name = (paths.Length == 1) ? "This Material" : "One or more of these Material(s)";
                    infotext.AppendLine(name + " has one or more children. Would you like to reparent all of these children to their closest remaining ancestor?");
                    int dialogOptionIndex = EditorUtility.DisplayDialogComplex(title, infotext.ToString(), L10n.Tr("Delete and reparent children"), L10n.Tr("Delete only"), L10n.Tr("Cancel"));
                    if (dialogOptionIndex == 0)
                    {
                        reparentMaterials = true;
                    }
                    else if (dialogOptionIndex == 2)
                    {
                        return(false);
                    }
                }
                else if (!EditorUtility.DisplayDialog(title, infotext.ToString(), L10n.Tr("Delete"), L10n.Tr("Cancel")))
                {
                    return(false);
                }
            }

            bool          success     = true;
            List <string> failedPaths = new List <string>();

            AssetDatabase.StartAssetEditing();

            if (reparentMaterials)
            {
                for (int i = 0; i < paths.Length; i++)
                {
                    if (paths[i].EndsWith(".mat", StringComparison.OrdinalIgnoreCase))
                    {
                        ReparentMaterialChildren(paths[i]);
                    }
                }
            }

            if (!AssetDatabase.MoveAssetsToTrash(paths, failedPaths))
            {
                success = false;
            }

            AssetDatabase.StopAssetEditing();

            if (!success)
            {
                var vcsOffline = false;
                if (!EditorUserSettings.WorkOffline)
                {
                    var vco = VersionControlManager.activeVersionControlObject;
                    if (vco != null)
                    {
                        vcsOffline = !vco.isConnected;
                    }
                    else if (Provider.enabled)
                    {
                        vcsOffline = !Provider.isActive;
                    }
                }
                var message = vcsOffline ?
                              L10n.Tr("Some assets could not be deleted.\nMake sure you are connected to your Version Control server or \"Work Offline\" is enabled.") :
                              L10n.Tr("Some assets could not be deleted.\nMake sure nothing is keeping a hook on them, like a loaded DLL for example.");

                EditorUtility.DisplayDialog(L10n.Tr("Cannot Delete"), message, L10n.Tr("Ok"));
            }

            PackageManager.Client.Resolve(false);

            return(success);
        }
        // Internal for testing framework
        internal void SaveDirtyPrefabAssets(bool reloadInspectors)
        {
            if (assetTargets == null)
            {
                return;
            }

            if (assetTarget == null)
            {
                return;
            }

            m_DirtyPrefabAssets.Clear();
            foreach (var asset in assetTargets)
            {
                // The asset could have been deleted when this method is called from OnDestroy().
                // E.g delete the selected prefab asset from the Project Browser.
                if (asset == null)
                {
                    continue;
                }

                if (!EditorUtility.IsPersistent(asset))
                {
                    continue;
                }

                if (!(asset is GameObject))
                {
                    continue;
                }

                var rootGameObject = (GameObject)asset;
                if (IsDirty(rootGameObject))
                {
                    string currentGuid    = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(rootGameObject));
                    var    changeTracking = new TrackedAsset()
                    {
                        asset = rootGameObject,
                        guid  = currentGuid,
                        hash  = AssetDatabase.GetSourceAssetFileHash(currentGuid)
                    };
                    m_DirtyPrefabAssets.Add(changeTracking);
                }
            }

            if (m_DirtyPrefabAssets.Count > 0)
            {
                AssetDatabase.StartAssetEditing();
                try
                {
                    foreach (var trackedAsset in m_DirtyPrefabAssets)
                    {
                        bool savedSuccesfully;
                        PrefabUtility.SavePrefabAsset(trackedAsset.asset, out savedSuccesfully);
                        if (!savedSuccesfully)
                        {
                            string title   = L10n.Tr("Saving Failed");
                            string message = L10n.Tr("Check the Console window to get more insight into what needs to be fixed on the Prefab Asset.\n\nYou can open Prefab Mode to fix any issues on child GameObjects");
                            EditorUtility.DisplayDialog(title, message, L10n.Tr("OK"));

                            m_SavingHasFailed = true;
                            break;
                        }
                    }
                }
                finally
                {
                    AssetDatabase.StopAssetEditing();

                    if (reloadInspectors)
                    {
                        foreach (var trackedAsset in m_DirtyPrefabAssets)
                        {
                            if (AssetDatabase.GetSourceAssetFileHash(trackedAsset.guid) != trackedAsset.hash)
                            {
                                // We only call ForceReloadInspectors (and not ForceRebuildInspectors) to ensure local inspector state
                                // is not destroyed, such as a foldout state maintained by an editor (case 1255013).
                                // And we need to reload Prefab asset inspectors in order for the preview to be regenerated since the preview shows
                                // an instantiated Prefab. E.g disable a MeshRenderer on a Prefab Asset and the mesh should be hidden in the preview.
                                EditorUtility.ForceReloadInspectors();
                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        void AllocationCallstacksToolbarItem()
        {
            if (Unsupported.IsDeveloperMode())
            {
                bool toggled        = m_SelectedMemRecordMode != ProfilerMemoryRecordMode.None;
                var  oldToggleState = toggled;
                if (EditorGUILayout.DropDownToggle(ref toggled, Styles.recordCallstacks, EditorStyles.toolbarDropDownToggle))
                {
                    Rect     rect  = GUILayoutUtility.topLevel.GetLast();
                    string[] names = new string[]
                    {
                        L10n.Tr("None"), L10n.Tr("Managed Allocations")
                    };
                    if (Unsupported.IsDeveloperMode())
                    {
                        names = new string[]
                        {
                            L10n.Tr("None"), L10n.Tr("Managed Allocations"), L10n.Tr("All Allocations (fast)"), L10n.Tr("All Allocations (full)")
                        };
                    }

                    var enabled = new bool[names.Length];
                    for (int c = 0; c < names.Length; ++c)
                    {
                        enabled[c] = true;
                    }
                    var selected = new int[] { (int)m_SelectedMemRecordMode };
                    EditorUtility.DisplayCustomMenu(rect, names, enabled, selected, MemRecordModeClick, null);
                    GUIUtility.ExitGUI();
                }
                if (toggled != oldToggleState)
                {
                    m_SelectedMemRecordMode = (m_SelectedMemRecordMode != ProfilerMemoryRecordMode.None) ? ProfilerMemoryRecordMode.None :
                                              (m_LastSelectedMemRecordMode == ProfilerMemoryRecordMode.None ? ProfilerMemoryRecordMode.ManagedAllocations : m_LastSelectedMemRecordMode);
                }
            }
            else
            {
                m_SelectedMemRecordMode = GUILayout.Toggle(m_SelectedMemRecordMode == ProfilerMemoryRecordMode.ManagedAllocations, Styles.recordCallstacks, EditorStyles.toolbarButton) ? ProfilerMemoryRecordMode.ManagedAllocations : ProfilerMemoryRecordMode.None;
            }
        }
Ejemplo n.º 10
0
        // *undocumented*
        private static string GetObjectTypeName(Object o)
        {
            if (o == null)
            {
                return("Nothing Selected");
            }

            if (o is GameObject)
            {
                return(o.name);
            }

            // Show "Tags & Layers" instead of "TagManager"
            if (o is TagManager)
            {
                return("Tags & Layers");
            }

            if (o is Component)
            {
                var behaviour = o as MonoBehaviour;
                if (behaviour)
                {
                    var scriptClassName = behaviour.GetScriptClassName();
                    if (scriptClassName == "InvalidStateMachineBehaviour")
                    {
                        return(behaviour.name + L10n.Tr(" (Script)"));
                    }
                    return(scriptClassName + L10n.Tr(" (Script)"));
                }

                var meshfilter = o as MeshFilter;
                if (meshfilter)
                {
                    var mesh = meshfilter.sharedMesh;
                    return((mesh ? mesh.name : "[none]") + " (MeshFilter)");
                }

                return(o.GetType().Name);
            }

            // Importers don't have names. Just show the type without parenthesis (like we do for components).
            if (o is AssetImporter)
            {
                var monoImporter = o as MonoImporter;
                if (monoImporter)
                {
                    var script = monoImporter.GetScript();
                    return("Default References (" + (script ? script.name : string.Empty) + ")");
                }

                if (NativeClassExtensionUtilities.ExtendsANativeType(o))
                {
                    var script = MonoScript.FromScriptedObject(o);
                    if (script != null)
                    {
                        return(script.GetClass().Name + L10n.Tr(" (Script)"));
                    }
                }

                return(o.GetType().Name);
            }

            return(o.name + " (" + o.GetType().Name + ")");
        }
Ejemplo n.º 11
0
        private void ListenForSecretCodes()
        {
            if (Event.current.type != EventType.KeyDown || (int)Event.current.character == 0)
            {
                return;
            }

            if (SecretCodeHasBeenTyped("internal", ref m_InternalCodeProgress))
            {
                bool enabled = !EditorPrefs.GetBool("DeveloperMode", false);
                EditorPrefs.SetBool("DeveloperMode", enabled);
                ShowNotification(new GUIContent(string.Format(L10n.Tr("Developer Mode {0}"), (enabled ? L10n.Tr("On") : L10n.Tr("Off")))));
                EditorUtility.RequestScriptReload();

                // Repaint all views to show/hide debug repaint indicator
                InternalEditorUtility.RepaintAllViews();
            }
        }
        protected override DragAndDropVisualMode HandleDragAndDrop(DragAndDropArgs args)
        {
            // Check if we can handle the current drag data (could be dragged in from other areas/windows in the editor)
            var draggedRows = DragAndDrop.GetGenericData(k_DragId) as List <int>;

            if (draggedRows == null || args.dragAndDropPosition != DragAndDropPosition.BetweenItems)
            {
                return(DragAndDropVisualMode.None);
            }

            if (args.performDrop)
            {
                if (m_Positions.hasMultipleDifferentValues)
                {
                    if (!EditorUtility.DisplayDialog(L10n.Tr("Moving an array element will copy the complete array to all other selected objects."),
                                                     L10n.Tr("Unique values in the different selected objects will be lost"),
                                                     L10n.Tr("OK"),
                                                     L10n.Tr("Cancel")))
                    {
                        return(DragAndDropVisualMode.Rejected);
                    }
                }

                int arraySize = GetArraySize();
                var newList   = new List <Vector3>(arraySize);
                draggedRows.Sort();

                int nextDragItem = 0;
                for (int i = 0; i < arraySize; ++i)
                {
                    if (i == args.insertAtIndex)
                    {
                        // Insert the items here
                        foreach (var viewItem in draggedRows)
                        {
                            newList.Add(m_Positions.GetArrayElementAtIndex(viewItem).vector3Value);
                        }
                    }

                    if (i == draggedRows[nextDragItem])
                    {
                        // Ignore this item, it is being moved
                        nextDragItem++;
                        if (nextDragItem >= draggedRows.Count)
                        {
                            nextDragItem = 0;
                        }
                    }
                    else
                    {
                        newList.Add(m_Positions.GetArrayElementAtIndex(i).vector3Value);
                    }
                }

                // Add to the end?
                if (args.insertAtIndex == arraySize)
                {
                    foreach (var viewItem in draggedRows)
                    {
                        newList.Add(m_Positions.GetArrayElementAtIndex(viewItem).vector3Value);
                    }
                }

                // Copy the list back
                for (int i = 0; i < arraySize; ++i)
                {
                    m_Positions.GetArrayElementAtIndex(i).vector3Value = newList[i];
                }

                SetSelection(Enumerable.Range(args.insertAtIndex - draggedRows.Count(o => o < args.insertAtIndex), draggedRows.Count).ToList());
            }
            return(DragAndDropVisualMode.Move);
        }
Ejemplo n.º 13
0
        internal static ShouldIncludeChildren DisplayUpdateChildrenDialogIfNeeded(IEnumerable <GameObject> gameObjects,
                                                                                  string title, string message)
        {
            if (!HasChildren(gameObjects))
            {
                return(ShouldIncludeChildren.HasNoChildren);
            }

            return
                ((ShouldIncludeChildren)
                 EditorUtility.DisplayDialogComplex(title, message, L10n.Tr("Yes, change children"), L10n.Tr("No, this object only"), L10n.Tr("Cancel")));
        }
Ejemplo n.º 14
0
        static void TryForceExitSafeMode()
        {
            if (EditorApplication.isCompiling)
            {
                EditorUtility.DisplayDialog(L10n.Tr("Exit Safe Mode blocked"), L10n.Tr("Cannot exit Safe Mode while compiling scripts"), L10n.Tr("Ok"));
                return;
            }

            if (EditorUtility.DisplayDialog(L10n.Tr("Exiting Safe Mode"),
                                            L10n.Tr("Are you sure you want to exit?\n\n" +
                                                    "Exiting Safe Mode while you still have compilation errors may cause your project to be in an incomplete or broken state. " +
                                                    "For example, packages in your project may fail to load, and your assets may not import correctly."),
                                            L10n.Tr("Cancel"), L10n.Tr("Exit Anyway")) == false) // the default btn is Cancel, when dialog returns true. Exit Anyway returns false.
            {
                EditorUtility.RequestPartialScriptReload();
            }
        }
Ejemplo n.º 15
0
        bool ApplyAll()
        {
            // Collect Prefab Asset paths and also check if there's more than one of the same.
            HashSet <string> prefabAssetPaths = new HashSet <string>();
            bool             multipleOfSame   = false;

            for (int i = 0; i < m_SelectedGameObjects.Length; i++)
            {
                string prefabAssetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_SelectedGameObjects[i]);
                if (prefabAssetPaths.Contains(prefabAssetPath))
                {
                    multipleOfSame = true;
                }
                else
                {
                    prefabAssetPaths.Add(prefabAssetPath);
                }
            }

            // If more than one instance of the same Prefab Asset, show dialog to user.
            if (multipleOfSame && !EditorUtility.DisplayDialog(
                    L10n.Tr("Multiple instances of same Prefab Asset"),
                    L10n.Tr("Multiple instances of the same Prefab Asset were detected. Potentially conflicting overrides will be applied sequentially and will overwrite each other."),
                    L10n.Tr("OK"),
                    L10n.Tr("Cancel")))
            {
                return(false);
            }

            // Make sure assets are checked out in version control.
            if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(prefabAssetPaths.ToArray(), PrefabUtility.SaveVerb.Apply))
            {
                return(false);
            }

            var undoStructs = new List <ApplyAllUndo>();
            var actionName  = "ApplyAll";

            for (var i = 0; i < m_SelectedGameObjects.Length; i++)
            {
                var us = new ApplyAllUndo();
                us.correspondingSourceObject = (GameObject)PrefabUtility.GetCorrespondingObjectFromSource(m_SelectedGameObjects[i]);
                Undo.RegisterFullObjectHierarchyUndo(us.correspondingSourceObject, actionName); // handles changes to existing objects and object what will be deleted but not objects that are created
                GameObject prefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(m_SelectedGameObjects[i]);
                Undo.RegisterFullObjectHierarchyUndo(prefabInstanceRoot, actionName);

                us.prefabHierarchy = new HashSet <int>();
                PrefabUtility.GetObjectListFromHierarchy(us.prefabHierarchy, us.correspondingSourceObject);
                undoStructs.Add(us);
            }

            // Apply sequentially.
            AssetDatabase.StartAssetEditing();
            try
            {
                foreach (var t in m_SelectedGameObjects)
                {
                    PrefabUtility.ApplyPrefabInstance(t, InteractionMode.UserAction);
                }
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }

            foreach (var t in undoStructs)
            {
                PrefabUtility.RegisterNewObjects(t.correspondingSourceObject, t.prefabHierarchy, actionName);
            }

            EditorUtility.ForceRebuildInspectors();
            return(true);
        }
Ejemplo n.º 16
0
        private void DrawMainToolbar()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);

            // Graph types
            Rect popupRect = GUILayoutUtility.GetRect(Styles.addArea, EditorStyles.toolbarDropDown, GUILayout.Width(Chart.kSideWidth));

            if (EditorGUI.DropdownButton(popupRect, Styles.addArea, FocusType.Passive, EditorStyles.toolbarDropDown))
            {
                int length   = m_Charts.Length;
                var names    = new string[length];
                var enabled  = new bool[length];
                var selected = new int[length];
                for (int c = 0; c < length; ++c)
                {
                    names[c]    = L10n.Tr(((ProfilerArea)c).ToString());
                    enabled[c]  = true;
                    selected[c] = m_Charts[c].active ? c : -1;
                }
                EditorUtility.DisplayCustomMenu(popupRect, names, enabled, selected, AddAreaClick, null);
            }

            // Engine attach
            ConnectionGUILayout.AttachToPlayerDropdown(m_AttachProfilerState, EditorStyles.toolbarDropDown);

            // Record
            var profilerEnabled = GUILayout.Toggle(m_Recording, m_Recording ? Styles.profilerRecordOn : Styles.profilerRecordOff, EditorStyles.toolbarButton);

            if (profilerEnabled != m_Recording)
            {
                ProfilerDriver.enabled = profilerEnabled;
                m_Recording            = profilerEnabled;
                SessionState.SetBool(kProfilerEnabledSessionKey, profilerEnabled);
            }

            FrameNavigationControls();

            using (new EditorGUI.DisabledScope(ProfilerDriver.lastFrameIndex == -1))
            {
                // Clear
                if (GUILayout.Button(Styles.clearData, EditorStyles.toolbarButton))
                {
                    Clear();
                }
            }

            // Separate File/Stream control elements from toggles
            GUILayout.FlexibleSpace();

            // Clear on Play
            SetClearOnPlay(GUILayout.Toggle(GetClearOnPlay(), Styles.clearOnPlay, EditorStyles.toolbarButton));

            using (new EditorGUI.DisabledScope(m_AttachProfilerState.connectedToTarget != ConnectionTarget.Editor))
            {
                // Deep profiling
                SetProfileDeepScripts(GUILayout.Toggle(ProfilerDriver.deepProfiling, Styles.deepProfile, EditorStyles.toolbarButton));
            }

            // Allocation callstacks
            AllocationCallstacksToolbarItem();

            // keep more space between the toggles and the overflow/help icon buttons on the far right, keep deep profiling closer to the other controls
            GUILayout.FlexibleSpace();
            GUILayout.FlexibleSpace();
            GUILayout.FlexibleSpace();

            // Load profile
            if (GUILayout.Button(Styles.loadProfilingData, EditorStyles.toolbarButton, GUILayout.MaxWidth(25)))
            {
                LoadProfilingData(Event.current.shift);
            }

            // Save profile
            using (new EditorGUI.DisabledScope(ProfilerDriver.lastFrameIndex == -1))
            {
                if (GUILayout.Button(Styles.saveProfilingData, EditorStyles.toolbarButton))
                {
                    SaveProfilingData();
                }
            }

            // Open Manual
            if (GUILayout.Button(Styles.helpButtonContent, EditorStyles.toolbarButton))
            {
                Application.OpenURL(Styles.linkToManual);
            }

            // Overflow Menu
            var overflowMenuRect = GUILayoutUtility.GetRect(Styles.optionsButtonContent, EditorStyles.toolbarButton);

            if (GUI.Button(overflowMenuRect, Styles.optionsButtonContent, EditorStyles.toolbarButton))
            {
                GenericMenu menu = new GenericMenu();
                menu.AddItem(Styles.accessibilityModeLabel, UserAccessiblitySettings.colorBlindCondition != ColorBlindCondition.Default, OnToggleColorBlindMode);
                menu.AddSeparator("");
                menu.AddItem(Styles.preferencesButtonContent, false, OpenProfilerPreferences);
                menu.DropDown(overflowMenuRect);
            }

            GUILayout.EndHorizontal();
        }
        private void DoLayerField(GameObject go)
        {
            EditorGUIUtility.labelWidth = Styles.layerFieldWidth;
            Rect layerRect = GUILayoutUtility.GetRect(GUIContent.none, Styles.layerPopup);

            EditorGUI.BeginProperty(layerRect, GUIContent.none, m_Layer);
            EditorGUI.BeginChangeCheck();
            int layer = EditorGUI.LayerField(layerRect, Styles.layerContent, go.layer, Styles.layerPopup);

            if (EditorGUI.EndChangeCheck())
            {
                GameObjectUtility.ShouldIncludeChildren includeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(targets.OfType <GameObject>(),
                                                                                                                                L10n.Tr("Change Layer"), string.Format(L10n.Tr("Do you want to set layer to {0} for all child objects as well?"), InternalEditorUtility.GetLayerName(layer)));
                if (includeChildren != GameObjectUtility.ShouldIncludeChildren.Cancel)
                {
                    m_Layer.intValue = layer;
                    SetLayer(layer, includeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren);
                }
                // Displaying the dialog to ask the user whether to update children nukes the gui state
                EditorGUIUtility.ExitGUI();
            }
            EditorGUI.EndProperty();
        }
Ejemplo n.º 18
0
        void OnEnable()
        {
            s_Window     = this;
            titleContent = EditorGUIUtility.TrTextContent("Background Tasks");

            rootVisualElement.AddStyleSheetPath(ussPath);
            if (EditorGUIUtility.isProSkin)
            {
                rootVisualElement.AddStyleSheetPath(ussPathDark);
            }
            else
            {
                rootVisualElement.AddStyleSheetPath(ussPathLight);
            }

            var toolbar = new UIElements.Toolbar();

            m_DismissAllBtn = new ToolbarButton(ClearInactive)
            {
                name = "DismissAllBtn",
                text = L10n.Tr("Clear inactive"),
            };
            toolbar.Add(m_DismissAllBtn);

            // This is our friend the spacer
            toolbar.Add(new VisualElement()
            {
                style =
                {
                    flexGrow = 1
                }
            });

            rootVisualElement.Add(toolbar);
            s_VisualProgressItemTask = EditorGUIUtility.Load(k_UxmlProgressItemPath) as VisualTreeAsset;

            m_TreeView                 = new TreeView();
            m_TreeView.makeItem        = MakeTreeViewItem;
            m_TreeView.bindItem        = BindTreeViewItem;
            m_TreeView.unbindItem      = UnbindTreeViewItem;
            m_TreeView.destroyItem     = DestroyTreeViewItem;
            m_TreeView.fixedItemHeight = 50;
            m_TreeView.SetRootItems(new TreeViewItemData <Progress.Item>[] {});

            var scrollView = m_TreeView.Q <ScrollView>();

            if (scrollView != null)
            {
                scrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
            }

            rootVisualElement.Add(m_TreeView);
            m_TreeView.Rebuild();

            // Update the treeview with the existing items
            m_MissingParents        = new Dictionary <int, List <int> >();
            m_ContainedItems        = new HashSet <int>();
            m_ItemsNeedingExpansion = new HashSet <int>();
            OperationsAdded(Progress.EnumerateItems().ToArray());

            Progress.added   += OperationsAdded;
            Progress.removed += OperationsRemoved;
            Progress.updated += OperationsUpdated;
            UpdateDismissAllButton();
        }
        void DoMaterialsGUI()
        {
            if (targets.Length > 1)
            {
                EditorGUILayout.HelpBox(L10n.Tr("Material Editing is not supported on multiple selection"), MessageType.Info);
                return;
            }

            serializedObject.UpdateIfRequiredOrScript();

            UpdateShowAllMaterialNameOptions();

            using (var horizontal = new EditorGUILayout.HorizontalScope())
            {
                using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.MaterialCreationMode, m_MaterialImportMode))
                {
                    EditorGUI.BeginChangeCheck();
                    var newValue = (int)(ModelImporterMaterialImportMode)EditorGUILayout.EnumPopup(prop.content, (ModelImporterMaterialImportMode)m_MaterialImportMode.intValue);
                    if (EditorGUI.EndChangeCheck())
                    {
                        m_MaterialImportMode.intValue = newValue;
                    }
                }
            }

            string materialHelp = string.Empty;

            if (!m_MaterialImportMode.hasMultipleDifferentValues)
            {
                if (m_MaterialImportMode.intValue != (int)ModelImporterMaterialImportMode.None)
                {
                    if (m_MaterialImportMode.intValue == (int)ModelImporterMaterialImportMode.ImportStandard)
                    {
                        EditorGUILayout.PropertyField(m_UseSRGBMaterialColor, Styles.SRGBMaterialColor);
                    }

                    using (var horizontal = new EditorGUILayout.HorizontalScope())
                    {
                        using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.MaterialLocation, m_MaterialLocation))
                        {
                            EditorGUI.BeginChangeCheck();
                            var newValue = (int)(ModelImporterMaterialLocation)EditorGUILayout.EnumPopup(prop.content, (ModelImporterMaterialLocation)m_MaterialLocation.intValue);
                            if (EditorGUI.EndChangeCheck())
                            {
                                m_MaterialLocation.intValue = newValue;
                            }
                        }
                    }

                    if (!m_MaterialLocation.hasMultipleDifferentValues)
                    {
                        if (m_MaterialLocation.intValue == 0)
                        {
                            // (legacy) we're generating materials in the Materials folder
                            EditorGUILayout.Popup(m_MaterialName,
                                                  m_ShowAllMaterialNameOptions ? Styles.MaterialNameOptAll : Styles.MaterialNameOptMain,
                                                  Styles.MaterialName);
                            EditorGUILayout.Popup(m_MaterialSearch, Styles.MaterialSearchOpt, Styles.MaterialSearch);

                            materialHelp =
                                Styles.ExternalMaterialHelpStart.text.Replace("%MAT%",
                                                                              Styles.ExternalMaterialNameHelp[m_MaterialName.intValue].text) + "\n" +
                                Styles.ExternalMaterialSearchHelp[m_MaterialSearch.intValue].text + "\n" +
                                Styles.ExternalMaterialHelpEnd.text;
                        }
                        else if (m_Materials.arraySize > 0 && m_CanExtractEmbeddedMaterials)
                        {
                            // we're generating materials inside the prefab
                            materialHelp = Styles.InternalMaterialHelp.text;
                        }
                    }

                    if (targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0)
                    {
                        materialHelp += " " + Styles.MaterialAssignmentsHelp.text;
                    }

                    // display the extract buttons
                    if (m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues)
                    {
                        ExtractTexturesGUI();
                        if (ExtractMaterialsGUI())
                        {
                            return;
                        }
                    }
                }
                else
                {
                    // we're not importing materials
                    materialHelp = Styles.NoMaterialHelp.text;
                }
            }

            if (!string.IsNullOrEmpty(materialHelp))
            {
                EditorGUILayout.HelpBox(materialHelp, MessageType.Info);
            }

            if ((targets.Length == 1 || m_SupportsEmbeddedMaterials.hasMultipleDifferentValues == false) && m_SupportsEmbeddedMaterials.boolValue == false &&
                m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues)
            {
                EditorGUILayout.Space();
                EditorGUILayout.HelpBox(Styles.NoMaterialMappingsHelp.text, MessageType.Warning);
            }

            // hidden for multi-selection
            if (m_MaterialImportMode.intValue != (int)ModelImporterMaterialImportMode.None && targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues && !m_Materials.hasMultipleDifferentValues && !m_ExternalObjects.hasMultipleDifferentValues)
            {
                GUILayout.Label(Styles.ExternalMaterialMappings, EditorStyles.boldLabel);

                MaterialRemapOptions();

                DoMaterialRemapList();
            }
        }
Ejemplo n.º 20
0
 public SubModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName)
     : base(owner, o, "SubModule", displayName)
 {
     m_ToolTip = L10n.Tr("Sub emission of particles. This allows each particle to emit particles in another system.");
     Init(); // Init when created because we need to query if we have any subemitters referenced
 }