Example #1
0
        private void EditorGUI_HyperLinkClicked(object sender, EventArgs e)
        {
            EditorGUILayout.HyperLinkClickedEventArgs args = (EditorGUILayout.HyperLinkClickedEventArgs)e;

            string filePath;
            string lineString;

            if (!args.hyperlinkInfos.TryGetValue("href", out filePath) ||
                !args.hyperlinkInfos.TryGetValue("line", out lineString))
            {
                return;
            }

            int line            = Int32.Parse(lineString);
            var projectFilePath = FileUtil.GetProjectRelativePath(filePath.Replace('\\', '/'));

            if (!String.IsNullOrEmpty(projectFilePath))
            {
                LogEntries.OpenFileOnSpecificLineAndColumn(filePath, line, -1);
            }
        }
Example #2
0
        internal static void ExtractSelectedObjectsFromPrefab()
        {
            var    assetsToReload = new HashSet <string>();
            string folder         = null;

            foreach (var selectedObj in Selection.objects)
            {
                var path = AssetDatabase.GetAssetPath(selectedObj);

                // use the first selected element as the basis for the folder path where all the materials will be extracted
                if (folder == null)
                {
                    folder = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(path), "");
                    if (string.IsNullOrEmpty(folder))
                    {
                        // cancel the extraction if the user did not select a folder
                        return;
                    }

                    folder = FileUtil.GetProjectRelativePath(folder);
                }

                // TODO: [bogdanc 3/6/2017] if we want this function really generic, we need to know what extension the new asset files should have
                var extension    = selectedObj is Material ? kMaterialExtension : string.Empty;
                var newAssetPath = FileUtil.CombinePaths(folder, selectedObj.name) + extension;
                newAssetPath = AssetDatabase.GenerateUniqueAssetPath(newAssetPath);

                var error = AssetDatabase.ExtractAsset(selectedObj, newAssetPath);
                if (string.IsNullOrEmpty(error))
                {
                    assetsToReload.Add(path);
                }
            }

            foreach (var path in assetsToReload)
            {
                AssetDatabase.WriteImportSettingsIfDirty(path);
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
            }
        }
Example #3
0
        private bool ExtractMaterialsGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Materials);
                using (new EditorGUI.DisabledScope(!HasEmbeddedMaterials()))
                {
                    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);
                        }
                        destinationPath = FileUtil.GetProjectRelativePath(destinationPath);

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();

                            PrefabUtility.ExtractMaterialsFromAsset(targets, destinationPath);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

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

            return(false);
        }
Example #4
0
        private HumanTemplate OpenHumanTemplate()
        {
            string        text  = "Assets/";
            string        text2 = EditorUtility.OpenFilePanel("Open Human Template", text, "ht");
            HumanTemplate result;

            if (text2 == "")
            {
                result = null;
            }
            else
            {
                string        projectRelativePath = FileUtil.GetProjectRelativePath(text2);
                HumanTemplate humanTemplate       = AssetDatabase.LoadMainAssetAtPath(projectRelativePath) as HumanTemplate;
                if (humanTemplate == null)
                {
                    if (EditorUtility.DisplayDialog("Human Template not found in project", "Import asset '" + text2 + "' into project", "Yes", "No"))
                    {
                        string text3 = text + FileUtil.GetLastPathNameComponent(text2);
                        text3 = AssetDatabase.GenerateUniqueAssetPath(text3);
                        FileUtil.CopyFileOrDirectory(text2, text3);
                        AssetDatabase.Refresh();
                        humanTemplate = (AssetDatabase.LoadMainAssetAtPath(text3) as HumanTemplate);
                        if (humanTemplate == null)
                        {
                            Debug.Log(string.Concat(new string[]
                            {
                                "Failed importing file '",
                                text2,
                                "' to '",
                                text3,
                                "'"
                            }));
                        }
                    }
                }
                result = humanTemplate;
            }
            return(result);
        }
Example #5
0
        internal static void ExtractSelectedObjectsFromPrefab()
        {
            HashSet <string> hashSet = new HashSet <string>();
            string           text    = null;

            UnityEngine.Object[] objects = Selection.objects;
            for (int i = 0; i < objects.Length; i++)
            {
                UnityEngine.Object @object   = objects[i];
                string             assetPath = AssetDatabase.GetAssetPath(@object);
                if (text == null)
                {
                    text = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(assetPath), "");
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    text = FileUtil.GetProjectRelativePath(text);
                }
                string str   = (!(@object is Material)) ? string.Empty : ".mat";
                string text2 = FileUtil.CombinePaths(new string[]
                {
                    text,
                    @object.name
                }) + str;
                text2 = AssetDatabase.GenerateUniqueAssetPath(text2);
                string value = AssetDatabase.ExtractAsset(@object, text2);
                if (string.IsNullOrEmpty(value))
                {
                    hashSet.Add(assetPath);
                }
            }
            foreach (string current in hashSet)
            {
                AssetDatabase.WriteImportSettingsIfDirty(current);
                AssetDatabase.ImportAsset(current, ImportAssetOptions.ForceUpdate);
            }
        }
Example #6
0
        private bool ExtractMaterialsGUI()
        {
            bool result;

            using (new EditorGUILayout.HorizontalScope(new GUILayoutOption[0]))
            {
                EditorGUILayout.PrefixLabel(ModelImporterMaterialEditor.Styles.Materials);
                using (new EditorGUI.DisabledScope(!this.HasEmbeddedMaterials()))
                {
                    if (GUILayout.Button(ModelImporterMaterialEditor.Styles.ExtractEmbeddedMaterials, new GUILayoutOption[0]))
                    {
                        string text = (base.target as ModelImporter).assetPath;
                        text = EditorUtility.SaveFolderPanel("Select Materials Folder", FileUtil.DeleteLastPathNameComponent(text), "");
                        if (string.IsNullOrEmpty(text))
                        {
                            result = false;
                            return(result);
                        }
                        text = FileUtil.GetProjectRelativePath(text);
                        try
                        {
                            AssetDatabase.StartAssetEditing();
                            PrefabUtility.ExtractMaterialsFromAsset(base.targets, text);
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }
                        result = true;
                        return(result);
                    }
                }
            }
            result = false;
            return(result);
        }
Example #7
0
        private HumanTemplate OpenHumanTemplate()
        {
            string directory = "Assets/";
            string str       = EditorUtility.OpenFilePanel("Open Human Template", directory, "ht");

            if (str == string.Empty)
            {
                return((HumanTemplate)null);
            }
            HumanTemplate humanTemplate = AssetDatabase.LoadMainAssetAtPath(FileUtil.GetProjectRelativePath(str)) as HumanTemplate;

            if ((UnityEngine.Object)humanTemplate == (UnityEngine.Object)null && EditorUtility.DisplayDialog("Human Template not found in project", "Import asset '" + str + "' into project", "Yes", "No"))
            {
                string uniqueAssetPath = AssetDatabase.GenerateUniqueAssetPath(directory + FileUtil.GetLastPathNameComponent(str));
                FileUtil.CopyFileOrDirectory(str, uniqueAssetPath);
                AssetDatabase.Refresh();
                humanTemplate = AssetDatabase.LoadMainAssetAtPath(uniqueAssetPath) as HumanTemplate;
                if ((UnityEngine.Object)humanTemplate == (UnityEngine.Object)null)
                {
                    Debug.Log((object)("Failed importing file '" + str + "' to '" + uniqueAssetPath + "'"));
                }
            }
            return(humanTemplate);
        }
Example #8
0
        public void OnGUI()
        {
            Event current = Event.current;
            bool  flag    = false;
            bool  flag2   = false;

            if (current.type == EventType.KeyDown)
            {
                flag  = (current.keyCode == KeyCode.Escape);
                flag2 = (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter);
            }
            using (HorizontalLayout.DoLayout())
            {
                GUILayout.Space(10f);
                using (VerticalLayout.DoLayout())
                {
                    GUILayout.FlexibleSpace();
                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TextContent("Publisher|Publisher of the package."), new GUILayoutOption[]
                        {
                            MetroCreateTestCertificateWindow.kLabelWidth
                        });
                        GUI.SetNextControlName("publisher");
                        this.publisher = GUILayout.TextField(this.publisher, new GUILayoutOption[0]);
                    }
                    GUILayout.Space(5f);
                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TextContent("Password|Certificate password."), new GUILayoutOption[]
                        {
                            MetroCreateTestCertificateWindow.kLabelWidth
                        });
                        GUI.SetNextControlName("password");
                        this.password = GUILayout.PasswordField(this.password, '●', new GUILayoutOption[0]);
                    }
                    GUILayout.Space(5f);
                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TextContent("Confirm password|Re-enter certificate password."), new GUILayoutOption[]
                        {
                            MetroCreateTestCertificateWindow.kLabelWidth
                        });
                        GUI.SetNextControlName("confirm");
                        this.confirm = GUILayout.PasswordField(this.confirm, '●', new GUILayoutOption[0]);
                    }
                    GUILayout.Space(10f);
                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(this.message, this.messageStyle, new GUILayoutOption[0]);
                        GUILayout.FlexibleSpace();
                        if (GUILayout.Button(EditorGUIUtility.TextContent("Create"), new GUILayoutOption[]
                        {
                            MetroCreateTestCertificateWindow.kButtonWidth
                        }) || flag2)
                        {
                            this.message = GUIContent.none;
                            if (string.IsNullOrEmpty(this.publisher))
                            {
                                this.message = EditorGUIUtility.TextContent("Publisher must be specified.");
                                this.focus   = "publisher";
                            }
                            else if (this.password != this.confirm)
                            {
                                if (string.IsNullOrEmpty(this.confirm))
                                {
                                    this.message = EditorGUIUtility.TextContent("Confirm the password.");
                                    this.focus   = "confirm";
                                }
                                else
                                {
                                    this.message  = EditorGUIUtility.TextContent("Passwords do not match.");
                                    this.password = string.Empty;
                                    this.confirm  = this.password;
                                    this.focus    = "password";
                                }
                            }
                            else
                            {
                                try
                                {
                                    EditorUtility.WSACreateTestCertificate(this.path, this.publisher, this.password, true);
                                    AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
                                    if (!PlayerSettings.WSA.SetCertificate(FileUtil.GetProjectRelativePath(this.path), this.password))
                                    {
                                        this.message = EditorGUIUtility.TextContent("Invalid password.");
                                    }
                                    flag = true;
                                }
                                catch (UnityException ex)
                                {
                                    Debug.LogError(ex.Message);
                                }
                            }
                        }
                    }
                    GUILayout.FlexibleSpace();
                }
                GUILayout.Space(10f);
            }
            if (flag)
            {
                base.Close();
            }
            else if (this.focus != null)
            {
                EditorGUI.FocusTextInControl(this.focus);
                this.focus = null;
            }
        }
Example #9
0
        private void ExtractTexturesGUI()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(Styles.Textures);

                using (
                    new EditorGUI.DisabledScope(!m_HasEmbeddedTextures.boolValue &&
                                                !m_HasEmbeddedTextures.hasMultipleDifferentValues))
                {
                    if (GUILayout.Button(Styles.ExtractEmbeddedTextures))
                    {
                        // when extracting textures, we must handle the case when multiple selected assets could generate textures with the same name at the user supplied path
                        // we proceed as follows:
                        // 1. each asset extracts the textures in a separate temp folder
                        // 2. we remap the extracted assets to the respective asset importer
                        // 3. we generate unique names for each asset and move them to the user supplied path
                        // 4. we re-import all the assets to have the internal materials linked to the newly extracted textures

                        List <Tuple <Object, string> > outputsForTargets = new List <Tuple <Object, string> >();
                        // 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 Textures Folder",
                                                                        FileUtil.DeleteLastPathNameComponent(destinationPath), "");
                        if (string.IsNullOrEmpty(destinationPath))
                        {
                            // cancel the extraction if the user did not select a folder
                            return;
                        }
                        destinationPath = FileUtil.GetProjectRelativePath(destinationPath);

                        try
                        {
                            // batch the extraction of the textures
                            AssetDatabase.StartAssetEditing();

                            foreach (var t in targets)
                            {
                                var tempPath = FileUtil.GetUniqueTempPathInProject();
                                tempPath = tempPath.Replace("Temp", UnityEditorInternal.InternalEditorUtility.GetAssetsFolder());
                                outputsForTargets.Add(Tuple.Create(t, tempPath));

                                var importer = t as ModelImporter;
                                importer.ExtractTextures(tempPath);
                            }
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }

                        try
                        {
                            // batch the remapping and the reimport of the assets
                            AssetDatabase.Refresh();
                            AssetDatabase.StartAssetEditing();

                            foreach (var item in outputsForTargets)
                            {
                                var importer = item.Item1 as ModelImporter;

                                var guids = AssetDatabase.FindAssets("t:Texture", new string[] { item.Item2 });

                                foreach (var guid in guids)
                                {
                                    var path = AssetDatabase.GUIDToAssetPath(guid);
                                    var tex  = AssetDatabase.LoadAssetAtPath <Texture>(path);
                                    if (tex == null)
                                    {
                                        continue;
                                    }

                                    importer.AddRemap(new AssetImporter.SourceAssetIdentifier(tex), tex);

                                    var newPath = Path.Combine(destinationPath, FileUtil.UnityGetFileName(path));
                                    newPath = AssetDatabase.GenerateUniqueAssetPath(newPath);
                                    AssetDatabase.MoveAsset(path, newPath);
                                }

                                AssetDatabase.ImportAsset(importer.assetPath, ImportAssetOptions.ForceUpdate);

                                AssetDatabase.DeleteAsset(item.Item2);
                            }
                        }
                        finally
                        {
                            AssetDatabase.StopAssetEditing();
                        }
                    }
                }
            }
        }
Example #10
0
        public static Dictionary <Vector2Int, TileBase> ConvertToTileSheet(Dictionary <Vector2Int, UnityEngine.Object> sheet)
        {
            Dictionary <Vector2Int, TileBase> dictionary = new Dictionary <Vector2Int, TileBase>();
            string text = (!ProjectBrowser.s_LastInteractedProjectBrowser) ? "Assets" : ProjectBrowser.s_LastInteractedProjectBrowser.GetActiveFolderPath();
            Dictionary <Vector2Int, TileBase> result;

            if (sheet.Values.ToList <UnityEngine.Object>().FindAll((UnityEngine.Object obj) => obj is TileBase).Count == sheet.Values.Count)
            {
                foreach (KeyValuePair <Vector2Int, UnityEngine.Object> current in sheet)
                {
                    dictionary.Add(current.Key, current.Value as TileBase);
                }
                result = dictionary;
            }
            else
            {
                TileDragAndDrop.UserTileCreationMode userTileCreationMode = TileDragAndDrop.UserTileCreationMode.Overwrite;
                string text2 = "";
                bool   flag  = sheet.Count > 1;
                if (flag)
                {
                    bool flag2 = false;
                    text2 = EditorUtility.SaveFolderPanel("Generate tiles into folder ", text, "");
                    text2 = FileUtil.GetProjectRelativePath(text2);
                    foreach (UnityEngine.Object current2 in sheet.Values)
                    {
                        if (current2 is Sprite)
                        {
                            string path = FileUtil.CombinePaths(new string[]
                            {
                                text2,
                                string.Format("{0}.{1}", current2.name, TileDragAndDrop.k_TileExtension)
                            });
                            if (File.Exists(path))
                            {
                                flag2 = true;
                                break;
                            }
                        }
                    }
                    if (flag2)
                    {
                        int num = EditorUtility.DisplayDialogComplex("Overwrite?", string.Format("Assets exist at {0}. Do you wish to overwrite existing assets?", text2), "Overwrite", "Create New Copy", "Reuse");
                        if (num != 0)
                        {
                            if (num != 1)
                            {
                                if (num == 2)
                                {
                                    userTileCreationMode = TileDragAndDrop.UserTileCreationMode.Reuse;
                                }
                            }
                            else
                            {
                                userTileCreationMode = TileDragAndDrop.UserTileCreationMode.CreateUnique;
                            }
                        }
                        else
                        {
                            userTileCreationMode = TileDragAndDrop.UserTileCreationMode.Overwrite;
                        }
                    }
                }
                else
                {
                    text2 = EditorUtility.SaveFilePanelInProject("Generate new tile", sheet.Values.First <UnityEngine.Object>().name, TileDragAndDrop.k_TileExtension, "Generate new tile", text);
                }
                if (string.IsNullOrEmpty(text2))
                {
                    result = dictionary;
                }
                else
                {
                    int num2 = 0;
                    EditorUtility.DisplayProgressBar(string.Concat(new object[]
                    {
                        "Generating Tile Assets (",
                        num2,
                        "/",
                        sheet.Count,
                        ")"
                    }), "Generating tiles", 0f);
                    foreach (KeyValuePair <Vector2Int, UnityEngine.Object> current3 in sheet)
                    {
                        string   text3 = "";
                        TileBase tileBase;
                        if (current3.Value is Sprite)
                        {
                            tileBase = TileDragAndDrop.CreateTile(current3.Value as Sprite);
                            text3    = ((!flag) ? text2 : FileUtil.CombinePaths(new string[]
                            {
                                text2,
                                string.Format("{0}.{1}", tileBase.name, TileDragAndDrop.k_TileExtension)
                            }));
                            if (userTileCreationMode != TileDragAndDrop.UserTileCreationMode.CreateUnique)
                            {
                                if (userTileCreationMode != TileDragAndDrop.UserTileCreationMode.Overwrite)
                                {
                                    if (userTileCreationMode == TileDragAndDrop.UserTileCreationMode.Reuse)
                                    {
                                        if (File.Exists(text3))
                                        {
                                            tileBase = AssetDatabase.LoadAssetAtPath <TileBase>(text3);
                                        }
                                        else
                                        {
                                            AssetDatabase.CreateAsset(tileBase, text3);
                                        }
                                    }
                                }
                                else
                                {
                                    AssetDatabase.CreateAsset(tileBase, text3);
                                }
                            }
                            else
                            {
                                if (File.Exists(text3))
                                {
                                    text3 = AssetDatabase.GenerateUniqueAssetPath(text3);
                                }
                                AssetDatabase.CreateAsset(tileBase, text3);
                            }
                        }
                        else
                        {
                            tileBase = (current3.Value as TileBase);
                        }
                        EditorUtility.DisplayProgressBar(string.Concat(new object[]
                        {
                            "Generating Tile Assets (",
                            num2,
                            "/",
                            sheet.Count,
                            ")"
                        }), "Generating " + text3, (float)num2++ / (float)sheet.Count);
                        dictionary.Add(current3.Key, tileBase);
                    }
                    EditorUtility.ClearProgressBar();
                    AssetDatabase.Refresh();
                    result = dictionary;
                }
            }
            return(result);
        }
        public void OnGUI()
        {
            var e     = Event.current;
            var close = false;
            var enter = false;

            if (e.type == EventType.KeyDown)
            {
                close = (e.keyCode == KeyCode.Escape);
                enter = ((e.keyCode == KeyCode.Return) || (e.keyCode == KeyCode.KeypadEnter));
            }

            using (HorizontalLayout.DoLayout())
            {
                GUILayout.Space(kSpace * 2);

                using (VerticalLayout.DoLayout())
                {
                    GUILayout.FlexibleSpace();

                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TrTextContent("Publisher", "Publisher of the package."), kLabelWidth);
                        GUI.SetNextControlName(kPublisherId);
                        publisher = GUILayout.TextField(publisher);
                    }

                    GUILayout.Space(kSpace);

                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TrTextContent("Password", "Certificate password."), kLabelWidth);
                        GUI.SetNextControlName(kPasswordId);
                        password = GUILayout.PasswordField(password, kPasswordChar);
                    }

                    GUILayout.Space(kSpace);

                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(EditorGUIUtility.TrTextContent("Confirm password", "Re-enter certificate password."), kLabelWidth);
                        GUI.SetNextControlName(kConfirmId);
                        confirm = GUILayout.PasswordField(confirm, kPasswordChar);
                    }

                    GUILayout.Space(kSpace * 2);

                    using (HorizontalLayout.DoLayout())
                    {
                        GUILayout.Label(message, messageStyle);

                        GUILayout.FlexibleSpace();

                        if (GUILayout.Button(EditorGUIUtility.TrTextContent("Create"), kButtonWidth) || enter)
                        {
                            message = GUIContent.none;

                            if (string.IsNullOrEmpty(publisher))
                            {
                                message = EditorGUIUtility.TrTextContent("Publisher must be specified.");
                                focus   = kPublisherId;
                            }

                            /*else if (!IsValidPublisher(publisher))
                             * {
                             *  message = EditorGUIUtility.TrTextContent("Invalid publisher.");
                             *  focus = kPublisherId;
                             * }*/
                            else if (password != confirm)
                            {
                                if (string.IsNullOrEmpty(confirm))
                                {
                                    message = EditorGUIUtility.TrTextContent("Confirm the password.");
                                    focus   = kConfirmId;
                                }
                                else
                                {
                                    message  = EditorGUIUtility.TrTextContent("Passwords do not match.");
                                    password = string.Empty;
                                    confirm  = password;
                                    focus    = kPasswordId;
                                }
                            }
                            else
                            {
                                try
                                {
                                    EditorUtility.WSACreateTestCertificate(path, publisher, password, true);

                                    AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);

                                    if (!PlayerSettings.WSA.SetCertificate(FileUtil.GetProjectRelativePath(path), password))
                                    {
                                        message = EditorGUIUtility.TrTextContent("Invalid password.");
                                    }

                                    close = true;
                                }
                                catch (UnityException ex)
                                {
                                    Debug.LogError(ex.Message);
                                }
                            }
                        }
                    }

                    GUILayout.FlexibleSpace();
                }

                GUILayout.Space(kSpace * 2);
            }

            if (close)
            {
                Close();
            }
            else if (focus != null)
            {
                EditorGUI.FocusTextInControl(focus);
                focus = null;
            }
        }
        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);
        }
        public static Dictionary <Vector2Int, TileBase> ConvertToTileSheet(Dictionary <Vector2Int, Object> sheet)
        {
            Dictionary <Vector2Int, TileBase> result = new Dictionary <Vector2Int, TileBase>();

            string defaultPath = ProjectBrowser.s_LastInteractedProjectBrowser
                ? ProjectBrowser.s_LastInteractedProjectBrowser.GetActiveFolderPath()
                : "Assets";

            // Early out if all objects are already tiles
            if (sheet.Values.ToList().FindAll(obj => obj is TileBase).Count == sheet.Values.Count)
            {
                foreach (KeyValuePair <Vector2Int, Object> item in sheet)
                {
                    result.Add(item.Key, item.Value as TileBase);
                }
                return(result);
            }

            UserTileCreationMode userTileCreationMode = UserTileCreationMode.Overwrite;
            string path          = "";
            bool   multipleTiles = sheet.Count > 1;

            if (multipleTiles)
            {
                bool userInterventionRequired = false;
                path = EditorUtility.SaveFolderPanel("Generate tiles into folder ", defaultPath, "");
                path = FileUtil.GetProjectRelativePath(path);

                // Check if this will overwrite any existing assets
                foreach (var item in sheet.Values)
                {
                    if (item is Sprite)
                    {
                        var tilePath = FileUtil.CombinePaths(path, String.Format("{0}.{1}", item.name, k_TileExtension));
                        if (File.Exists(tilePath))
                        {
                            userInterventionRequired = true;
                            break;
                        }
                    }
                }
                // There are existing tile assets in the folder with names matching the items to be created
                if (userInterventionRequired)
                {
                    var option = EditorUtility.DisplayDialogComplex("Overwrite?", String.Format("Assets exist at {0}. Do you wish to overwrite existing assets?", path), "Overwrite", "Create New Copy", "Reuse");
                    switch (option)
                    {
                    case 0:     // Overwrite
                    {
                        userTileCreationMode = UserTileCreationMode.Overwrite;
                    }
                    break;

                    case 1:     // Create New Copy
                    {
                        userTileCreationMode = UserTileCreationMode.CreateUnique;
                    }
                    break;

                    case 2:     // Reuse
                    {
                        userTileCreationMode = UserTileCreationMode.Reuse;
                    }
                    break;
                    }
                }
            }
            else
            {
                // Do not check if this will overwrite new tile as user has explicitly selected the file to save to
                path = EditorUtility.SaveFilePanelInProject("Generate new tile", sheet.Values.First().name, k_TileExtension, "Generate new tile", defaultPath);
            }

            if (string.IsNullOrEmpty(path))
            {
                return(result);
            }

            int i = 0;

            EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating tiles", 0f);
            foreach (KeyValuePair <Vector2Int, Object> item in sheet)
            {
                TileBase tile;
                string   tilePath = "";
                if (item.Value is Sprite)
                {
                    tile     = CreateTile(item.Value as Sprite);
                    tilePath = multipleTiles
                        ? FileUtil.CombinePaths(path, String.Format("{0}.{1}", tile.name, k_TileExtension))
                        : path;
                    switch (userTileCreationMode)
                    {
                    case UserTileCreationMode.CreateUnique:
                    {
                        if (File.Exists(tilePath))
                        {
                            tilePath = AssetDatabase.GenerateUniqueAssetPath(tilePath);
                        }
                        AssetDatabase.CreateAsset(tile, tilePath);
                    }
                    break;

                    case UserTileCreationMode.Overwrite:
                    {
                        AssetDatabase.CreateAsset(tile, tilePath);
                    }
                    break;

                    case UserTileCreationMode.Reuse:
                    {
                        if (File.Exists(tilePath))
                        {
                            tile = AssetDatabase.LoadAssetAtPath <TileBase>(tilePath);
                        }
                        else
                        {
                            AssetDatabase.CreateAsset(tile, tilePath);
                        }
                    }
                    break;
                    }
                }
                else
                {
                    tile = item.Value as TileBase;
                }
                EditorUtility.DisplayProgressBar("Generating Tile Assets (" + i + "/" + sheet.Count + ")", "Generating " + tilePath, (float)i++ / sheet.Count);
                result.Add(item.Key, tile);
            }
            EditorUtility.ClearProgressBar();

            AssetDatabase.Refresh();
            return(result);
        }
Example #14
0
 private void ExtractTexturesGUI()
 {
     using (new EditorGUILayout.HorizontalScope(new GUILayoutOption[0]))
     {
         EditorGUILayout.PrefixLabel(ModelImporterMaterialEditor.Styles.Textures);
         using (new EditorGUI.DisabledScope(!this.m_HasEmbeddedTextures.boolValue && !this.m_HasEmbeddedTextures.hasMultipleDifferentValues))
         {
             if (GUILayout.Button(ModelImporterMaterialEditor.Styles.ExtractEmbeddedTextures, new GUILayoutOption[0]))
             {
                 List <Tuple <UnityEngine.Object, string> > list = new List <Tuple <UnityEngine.Object, string> >();
                 string text = (base.target as ModelImporter).assetPath;
                 text = EditorUtility.SaveFolderPanel("Select Textures Folder", FileUtil.DeleteLastPathNameComponent(text), "");
                 if (!string.IsNullOrEmpty(text))
                 {
                     text = FileUtil.GetProjectRelativePath(text);
                     try
                     {
                         AssetDatabase.StartAssetEditing();
                         UnityEngine.Object[] targets = base.targets;
                         for (int i = 0; i < targets.Length; i++)
                         {
                             UnityEngine.Object @object = targets[i];
                             string             text2   = FileUtil.GetUniqueTempPathInProject();
                             text2 = text2.Replace("Temp", InternalEditorUtility.GetAssetsFolder());
                             list.Add(Tuple.Create <UnityEngine.Object, string>(@object, text2));
                             ModelImporter modelImporter = @object as ModelImporter;
                             modelImporter.ExtractTextures(text2);
                         }
                     }
                     finally
                     {
                         AssetDatabase.StopAssetEditing();
                     }
                     try
                     {
                         AssetDatabase.Refresh();
                         AssetDatabase.StartAssetEditing();
                         foreach (Tuple <UnityEngine.Object, string> current in list)
                         {
                             ModelImporter modelImporter2 = current.Item1 as ModelImporter;
                             string[]      array          = AssetDatabase.FindAssets("t:Texture", new string[]
                             {
                                 current.Item2
                             });
                             string[] array2 = array;
                             for (int j = 0; j < array2.Length; j++)
                             {
                                 string  guid    = array2[j];
                                 string  text3   = AssetDatabase.GUIDToAssetPath(guid);
                                 Texture texture = AssetDatabase.LoadAssetAtPath <Texture>(text3);
                                 if (!(texture == null))
                                 {
                                     modelImporter2.AddRemap(new AssetImporter.SourceAssetIdentifier(texture), texture);
                                     string text4 = Path.Combine(text, FileUtil.UnityGetFileName(text3));
                                     text4 = AssetDatabase.GenerateUniqueAssetPath(text4);
                                     AssetDatabase.MoveAsset(text3, text4);
                                 }
                             }
                             AssetDatabase.ImportAsset(modelImporter2.assetPath, ImportAssetOptions.ForceUpdate);
                             AssetDatabase.DeleteAsset(current.Item2);
                         }
                     }
                     finally
                     {
                         AssetDatabase.StopAssetEditing();
                     }
                 }
             }
         }
     }
 }