internal static IEnumerable <Object> DuplicateAssets(IEnumerable <Object> assets) { AssetDatabase.Refresh(); var copiedPaths = new List <string>(); Object firstDuplicatedObjectToFail = null; foreach (var asset in assets) { var assetPath = AssetDatabase.GetAssetPath(asset); // if duplicating a sub-asset, then create a copy next to the main asset file if (!String.IsNullOrEmpty(assetPath) && AssetDatabase.IsSubAsset(asset)) { if (asset is ISubAssetNotDuplicatable) { firstDuplicatedObjectToFail = firstDuplicatedObjectToFail ? firstDuplicatedObjectToFail : asset; continue; } var extension = NativeFormatImporterUtility.GetExtensionForAsset(asset); // We dot sanitize or block unclean the asset filename (asset.name) // since the assertdb will do it for us and has a whole tailored logic for that. // It feels wrong that the asset name (that can apparently contain any char) // is conflated with the orthogonal notion of filename. From the user's POV // it will force an asset dup but with mangled names if the original name contained // "invalid chars" for filenames. // Path.Combine is not used here to avoid blocking asset names that might // contain chars not allowed in filenames. if ((new HashSet <char>(Path.GetInvalidFileNameChars())).Intersect(asset.name).Count() != 0) { Debug.LogWarning(string.Format("Duplicated asset name '{0}' contains invalid characters. Those will be replaced in the duplicated asset name.", asset.name)); } var newPath = AssetDatabase.GenerateUniqueAssetPath( string.Format("{0}{1}{2}.{3}", Path.GetDirectoryName(assetPath), Path.DirectorySeparatorChar, asset.name, extension) ); AssetDatabase.CreateAsset(Object.Instantiate(asset), newPath); copiedPaths.Add(newPath); } // otherwise duplicate the main asset file else if (EditorUtility.IsPersistent(asset)) { var newPath = AssetDatabase.GenerateUniqueAssetPath(assetPath); if (newPath.Length > 0 && AssetDatabase.CopyAsset(assetPath, newPath)) { copiedPaths.Add(newPath); } } } if (firstDuplicatedObjectToFail != null) { var errString = string.Format( "Duplication error: One or more sub assets (with types of {0}) can not be duplicated directly, use the appropriate editor instead", firstDuplicatedObjectToFail.GetType().Name ); Debug.LogError(errString, firstDuplicatedObjectToFail); } AssetDatabase.Refresh(); return(copiedPaths.Select(AssetDatabase.LoadMainAssetAtPath)); }
internal static void DuplicateSelectedAssets() { AssetDatabase.Refresh(); UnityEngine.Object[] objects = Selection.objects; bool flag = true; UnityEngine.Object[] array = objects; for (int i = 0; i < array.Length; i++) { UnityEngine.Object @object = array[i]; AnimationClip animationClip = @object as AnimationClip; if (animationClip == null || (animationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None || !AssetDatabase.Contains(animationClip)) { flag = false; } } ArrayList arrayList = new ArrayList(); bool flag2 = false; if (flag) { UnityEngine.Object[] array2 = objects; for (int j = 0; j < array2.Length; j++) { UnityEngine.Object object2 = array2[j]; AnimationClip animationClip2 = object2 as AnimationClip; if (animationClip2 != null && (animationClip2.hideFlags & HideFlags.NotEditable) != HideFlags.None) { string path = AssetDatabase.GetAssetPath(object2); path = Path.Combine(Path.GetDirectoryName(path), animationClip2.name) + ".anim"; string text = AssetDatabase.GenerateUniqueAssetPath(path); AnimationClip animationClip3 = new AnimationClip(); EditorUtility.CopySerialized(animationClip2, animationClip3); AssetDatabase.CreateAsset(animationClip3, text); arrayList.Add(text); } } } else { UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); UnityEngine.Object[] array3 = filtered; for (int k = 0; k < array3.Length; k++) { UnityEngine.Object assetObject = array3[k]; string assetPath = AssetDatabase.GetAssetPath(assetObject); string text2 = AssetDatabase.GenerateUniqueAssetPath(assetPath); if (text2.Length != 0) { flag2 |= !AssetDatabase.CopyAsset(assetPath, text2); } else { flag2 |= true; } if (!flag2) { arrayList.Add(text2); } } } AssetDatabase.Refresh(); UnityEngine.Object[] array4 = new UnityEngine.Object[arrayList.Count]; for (int l = 0; l < arrayList.Count; l++) { array4[l] = AssetDatabase.LoadMainAssetAtPath(arrayList[l] as string); } Selection.objects = array4; }
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); }
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(); } } } } }
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); }
internal static void DuplicateSelectedAssets() { AssetDatabase.Refresh(); UnityEngine.Object[] objects = Selection.objects; bool flag = true; foreach (UnityEngine.Object obj2 in objects) { AnimationClip clip = obj2 as AnimationClip; if (((clip == null) || ((clip.hideFlags & HideFlags.NotEditable) == HideFlags.None)) || !AssetDatabase.Contains(clip)) { flag = false; } } ArrayList list = new ArrayList(); bool flag2 = false; if (flag) { foreach (UnityEngine.Object obj3 in objects) { AnimationClip source = obj3 as AnimationClip; if ((source != null) && ((source.hideFlags & HideFlags.NotEditable) != HideFlags.None)) { string path = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(Path.GetDirectoryName(AssetDatabase.GetAssetPath(obj3)), source.name) + ".anim"); AnimationClip dest = new AnimationClip(); EditorUtility.CopySerialized(source, dest); AssetDatabase.CreateAsset(dest, path); list.Add(path); } } } else { UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), UnityEditor.SelectionMode.Assets); foreach (UnityEngine.Object obj4 in filtered) { string assetPath = AssetDatabase.GetAssetPath(obj4); string newPath = AssetDatabase.GenerateUniqueAssetPath(assetPath); if (newPath.Length != 0) { flag2 |= !AssetDatabase.CopyAsset(assetPath, newPath); } else { flag2 |= true; } if (!flag2) { list.Add(newPath); } } } AssetDatabase.Refresh(); UnityEngine.Object[] objArray6 = new UnityEngine.Object[list.Count]; for (int i = 0; i < list.Count; i++) { objArray6[i] = AssetDatabase.LoadMainAssetAtPath(list[i] as string); } Selection.objects = objArray6; }
private void BakeCustomReflectionProbe(ReflectionProbe probe, bool usePreviousAssetPath) { string str1 = string.Empty; if (usePreviousAssetPath) { str1 = AssetDatabase.GetAssetPath((UnityEngine.Object)probe.customBakedTexture); } string extension = !probe.hdr ? "png" : "exr"; if (string.IsNullOrEmpty(str1) || Path.GetExtension(str1) != "." + extension) { string str2 = FileUtil.GetPathWithoutExtension(SceneManager.GetActiveScene().path); if (string.IsNullOrEmpty(str2)) { str2 = "Assets"; } else if (!Directory.Exists(str2)) { Directory.CreateDirectory(str2); } string path2 = probe.name + (!probe.hdr ? "-reflection" : "-reflectionHDR") + "." + extension; str1 = EditorUtility.SaveFilePanelInProject("Save reflection probe's cubemap.", Path.GetFileNameWithoutExtension(AssetDatabase.GenerateUniqueAssetPath(Path.Combine(str2, path2))), extension, string.Empty, str2); ReflectionProbe collidingProbe; if (string.IsNullOrEmpty(str1) || this.IsCollidingWithOtherProbes(str1, probe, out collidingProbe) && !EditorUtility.DisplayDialog("Cubemap is used by other reflection probe", string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?", (object)str1, (object)collidingProbe.name), "Yes", "No")) { return; } } EditorUtility.DisplayProgressBar("Reflection Probes", "Baking " + str1, 0.5f); if (!Lightmapping.BakeReflectionProbe(probe, str1)) { Debug.LogError((object)("Failed to bake reflection probe to " + str1)); } EditorUtility.ClearProgressBar(); }
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(); } } } } } }
public bool BeginNewAssetCreation(int instanceID, EndNameEditAction newAssetEndAction, string filePath, Texture2D icon, string newAssetResourceFile) { string filePath1 = filePath.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase) ? AssetDatabase.GenerateUniqueAssetPath(filePath) : AssetDatabase.GetUniquePathNameAtSelectedPath(filePath); if (!CreateAssetUtility.IsPathDataValid(filePath1)) { Debug.LogErrorFormat("Invalid generated unique path '{0}' (input path '{1}')", new object[2] { (object)filePath1, (object)filePath }); this.Clear(); return(false); } this.m_InstanceID = instanceID; this.m_Path = filePath1; this.m_Icon = icon; this.m_EndAction = newAssetEndAction; this.m_ResourceFile = newAssetResourceFile; Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); return(true); }