void OnGUI() { GUIStyle titleStyle = new GUIStyle(EditorStyles.centeredGreyMiniLabel); titleStyle.normal.textColor = Color.grey; titleStyle.fontSize = 12; titleStyle.fontStyle = FontStyle.Bold; GUILayout.Label("MergeCubeSDK Updater :", titleStyle); GUILayout.Space(5); GUILayout.Label("This tool will move the old MergeCubeSDK items from the root plugins folder to the MergeCubeSDK folder to help maintain asset file organization.", EditorStyles.wordWrappedLabel); GUILayout.Space(10); if (GUILayout.Button("Clean MergeCubeSDK")) { if (AssetDatabase.IsValidFolder("Assets/MergeCubeSDK")) { if (!AssetDatabase.IsValidFolder("Assets/MergeCubeSDK/Plugins")) { AssetDatabase.CreateFolder("Assets/MergeCubeSDK", "Plugins"); AssetDatabase.CreateFolder("Assets/MergeCubeSDK/Plugins", "Android"); AssetDatabase.CreateFolder("Assets/MergeCubeSDK/Plugins", "iOS"); AssetDatabase.CreateFolder("Assets/MergeCubeSDK/Plugins", "iVidCapPro"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } else { Debug.LogError("MergeCubeSDK Folder not found. Please ensure it has been imported and exists in the Asset root: Assets/MergeCubeSDK/"); } for (int index = 0; index < androidFilesToMove.Length; index++) { AssetDatabase.MoveAsset(androidFilesToMove[index], androidFilesToMove[index].Replace("Assets/Plugins/Android/", "Assets/MergeCubeSDK/Plugins/Android/")); } for (int index = 0; index < iOSFilesToMove.Length; index++) { AssetDatabase.MoveAsset(iOSFilesToMove[index], iOSFilesToMove[index].Replace("Assets/Plugins/iOS/", "Assets/MergeCubeSDK/Plugins/iOS/")); } for (int index = 0; index < iVidCapProFilesToMove.Length; index++) { AssetDatabase.MoveAsset(iVidCapProFilesToMove[index], iVidCapProFilesToMove[index].Replace("Assets/Plugins/iVidCapPro/", "Assets/MergeCubeSDK/Plugins/iVidCapPro/")); } for (int index = 0; index < filesToDelete.Length; index++) { AssetDatabase.DeleteAsset(filesToDelete[index]); } RemoveEmptyFolders("Assets/Plugins"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } GUILayout.Space(30); GUILayout.Label("EXPERIMENTAL : Vuforia 2017.2 Updater :", titleStyle); GUILayout.Label("This will delete the 2017.1 and older Vuforia files so you can cleanly import the new Vuforia files via the internal importer.", EditorStyles.wordWrappedLabel); GUILayout.Label("To do this manually, please refer to the documentation provided by Vuforia:\n\nhttps://library.vuforia.com/content/vuforia-library/en/articles/Solution/migrate-vuforia-62-to-65.html", EditorStyles.wordWrappedLabel); GUILayout.Label("USE AT YOUR OWN RISK", titleStyle); GUILayout.Space(10); if (GUILayout.Button("Strip Vuforia")) { for (int index = 0; index < vuforiaFilesToDelete.Length; index++) { AssetDatabase.DeleteAsset(vuforiaFilesToDelete[index]); } RemoveEmptyFolders("Assets/Plugins"); } GUILayout.Space(15); if (GUILayout.Button("Cancel")) { this.Close(); } }
public static void DeleteSettingsInstanceAdvanced() { AssetDatabase.DeleteAsset(AdvancedSettingsPath); }
/*private void Backup(TilerMap map) * { * var prefab = PrefabUtility.GetPrefabParent(map.gameObject); * var mapPath = AssetDatabase.GetAssetPath(prefab); * * if (string.IsNullOrEmpty(mapPath)) * { * return; * } * * // Potential Backup * var backupMapPath = mapPath + ".backup.prefab"; * var backup = AssetDatabase.LoadAssetAtPath(backupMapPath, typeof (GameObject)) as GameObject; * * if (backup == null) * { * PrefabUtility.CreatePrefab(backupMapPath, TilerMap.gameObject); * } * else * { * PrefabUtility.ReplacePrefab((GameObject)prefab, backup); * } * }*/ private void SaveMap(TilerMap map) { var prefab = PrefabUtility.GetPrefabParent(map.gameObject); var mapPath = AssetDatabase.GetAssetPath(prefab); if (string.IsNullOrEmpty(mapPath)) { Debug.LogError("Unable to save \"" + map.name + "\": Prefab has been deleted. Create a prefab, attach the gameobject and try save again."); // Set all cells to dirty so when attached, all will save out. foreach (var cell in map.Cells) { cell.IsDirty = true; } return; } // Check if we actually save anything. If not don't override prefab. This greatly improves performance. var isDoUpdate = false; // Setup paths var fullPath = Application.dataPath; var strippedPath = Path.GetDirectoryName(mapPath) + "/" + Path.GetFileNameWithoutExtension(mapPath) + "/"; var index = fullPath.IndexOf("Assets", StringComparison.Ordinal); if (index == -1) { return; } fullPath = fullPath.Substring(0, index); fullPath += strippedPath; // Check if directory exists, if not create it if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } // We share the mesh between all cells if (!map.SharedMesh) { return; } if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(map.SharedMesh))) { AssetDatabase.DeleteAsset(strippedPath + map.SharedMesh.name + ".asset"); AssetDatabase.CreateAsset(map.SharedMesh, strippedPath + map.SharedMesh.name + ".asset"); } var meshAsset = (Mesh)AssetDatabase.LoadAssetAtPath(strippedPath + map.SharedMesh.name + ".asset", typeof(Mesh)); foreach (var cell in map.Cells) { if (cell == null) { continue; } var go = cell.gameObject; if (!go.GetComponent <Renderer>()) { continue; } var mat = go.GetComponent <Renderer>().sharedMaterial; if (!mat) { continue; } // Render queue doesn't serialize out so we save it seperately. int renderQueue = mat.renderQueue; // Only update texture on changes if (cell.IsDirty) { cell.IsDirty = false; isDoUpdate = true; // Save the mesh as it may not have been done go.GetComponent <MeshFilter>().sharedMesh = meshAsset; var tex = (Texture2D)mat.mainTexture; // Store data before destroying var bytes = tex.EncodeToPNG(); var texName = tex.name; // Clean up old texture - stop memory leaks Object.DestroyImmediate(tex, true); // First we save the texture as a png, this lets us modify import properties compared to saving it as an asset Util.SaveTextureToFile(bytes, strippedPath + texName + ".png"); AssetDatabase.Refresh(); // Load the now saved png var texAsset = (Texture2D)AssetDatabase.LoadAssetAtPath(strippedPath + texName + ".png", typeof(Texture2D)); // Assign texture importer settings var path = AssetDatabase.GetAssetPath(texAsset); EditorUtil.SetTextureImportSettings(path, TilerMap.TextureResolution); // Assign this new texture to the material mat.mainTexture = texAsset; // If material doesn't exist if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(mat))) { AssetDatabase.DeleteAsset(strippedPath + mat.name + ".mat"); AssetDatabase.CreateAsset(mat, strippedPath + mat.name + ".mat"); // Load the new material var matAsset = (Material)AssetDatabase.LoadAssetAtPath(strippedPath + mat.name + ".mat", typeof(Material)); // Assign this new material/mesh to the go go.GetComponent <Renderer>().sharedMaterial = matAsset; } } // Always apply renderqueue update go.GetComponent <Renderer>().sharedMaterial.renderQueue = renderQueue; } var prefabMap = ((GameObject)prefab).GetComponent <TilerMap>(); // do a check of tilermap properties to see if we need to update if (prefabMap.Layer != map.Layer || prefabMap.DefaultShader != map.DefaultShader) { isDoUpdate = true; } // Only replace if something changed. Adds a lot of annoying checks but much better performance if (isDoUpdate) { PrefabUtility.ReplacePrefab(map.gameObject, prefab, ReplacePrefabOptions.ConnectToPrefab); } }
private static void GenerateREADME() { var guidMaterial = new Material(Shader.Find("Unlit/Texture")); var guidMaterialId = "Assets/Editor/GuidMaterial.mat"; AssetDatabase.CreateAsset(guidMaterial, guidMaterialId); EditorUtility.DisplayProgressBar("Generate README.md", "Generating...", 0.0f); try { var editorAssetBundle = GetEditorAssetBundle(); var iconsPath = GetIconsPath(); var readmeContents = new StringBuilder(); readmeContents.AppendLine($"Unity Editor Built-in Icons"); readmeContents.AppendLine($"=============================="); readmeContents.AppendLine($"Unity version: {Application.unityVersion}"); readmeContents.AppendLine($"Icons what can load using `EditorGUIUtility.IconContent`"); readmeContents.AppendLine(); readmeContents.AppendLine($"File ID"); readmeContents.AppendLine($"-------------"); readmeContents.AppendLine($"You can change script icon by file id"); readmeContents.AppendLine($"1. Open `*.cs.meta` in Text Editor"); readmeContents.AppendLine($"2. Modify line `icon: {{instanceID: 0}}` to `icon: {{fileID: <FILE ID>, guid: 0000000000000000d000000000000000, type: 0}}`"); readmeContents.AppendLine($"3. Save and focus Unity Editor"); readmeContents.AppendLine(); readmeContents.AppendLine($"| Icon | Name | File ID |"); readmeContents.AppendLine($"|------|------|---------|"); var assetNames = EnumerateIcons(editorAssetBundle, iconsPath).ToArray(); for (var i = 0; i < assetNames.Length; i++) { var assetName = assetNames[i]; var icon = editorAssetBundle.LoadAsset <Texture2D>(assetName); if (icon == null) { continue; } EditorUtility.DisplayProgressBar("Generate README.md", $"Generating... ({i + 1}/{assetNames.Length})", (float)i / assetNames.Length); var readableTexture = new Texture2D(icon.width, icon.height, icon.format, icon.mipmapCount > 1); Graphics.CopyTexture(icon, readableTexture); var folderPath = Path.GetDirectoryName(Path.Combine("icons/small/", assetName.Substring(iconsPath.Length))); if (Directory.Exists(folderPath) == false) { Directory.CreateDirectory(folderPath); } var iconPath = Path.Combine(folderPath, icon.name + ".png"); File.WriteAllBytes(iconPath, readableTexture.EncodeToPNG()); // guidMaterial.mainTexture = icon; EditorUtility.SetDirty(guidMaterial); AssetDatabase.SaveAssets(); var fileId = GetFileId(guidMaterialId); var escapedUrl = iconPath.Replace(" ", "%20").Replace('\\', '/'); readmeContents.AppendLine($"| ![]({escapedUrl}) | `{icon.name}` | `{fileId}` |"); } File.WriteAllText("README.md", readmeContents.ToString()); Debug.Log($"'READMD.md' has been generated."); } finally { EditorUtility.ClearProgressBar(); AssetDatabase.DeleteAsset(guidMaterialId); } }
static void Update() { if (CheckIfProjectSwitchNeeded()) { return; } if (EditorApplication.isPlaying) { if (!AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - Unity is using the project")) { if (buildNotReady) { // do not allow running at an inconsistent state Debug.LogError("Cannot play because MAGIS project is in an inconsistent state. Please fix any issues that weren't resolved by Autorun.CleanUp() and reload the project."); EditorApplication.isPlaying = false; return; } buildNotReady = true; // upon running, hide unnecessary resources AssetDatabase.CreateFolder("Assets", "_DO NOT COMMIT RIGHT NOW - Unity is using the project"); AssetDatabase.Refresh(); // force editor to play at 1x scale or lower Type type = typeof(EditorWindow).Assembly.GetType("UnityEditor.GameView"); EditorWindow w = EditorWindow.GetWindow(type); var areaField = type.GetField("m_ZoomArea", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var areaObj = areaField.GetValue(w); var scaleField = areaObj.GetType().GetField("m_Scale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); Vector2 value = (Vector2)scaleField.GetValue(areaObj); if (value.x > 1.0f) { scaleField.SetValue(areaObj, new Vector2(1.0f, 1.0f)); } loadedLevel = null; if (GameObject.FindWithTag("ARMarker") != null && GameObject.FindWithTag("AREngine") == null) { // temporarily halt the loading of an AR editor level to load CommonScene loadedLevel = SceneManager.GetActiveScene().name; SceneManager.LoadScene("CommonScene"); DeviceInput.RequestCameraPermission(); Debug.Log("Starting ARScene"); } else if (GameObject.Find("GameState") == null) { // for other levels that come with arengine, always run from the beginning if (SceneManager.GetActiveScene().name == "ARScene" || SceneManager.GetActiveScene().name == "ARSubscene" || SceneManager.GetActiveScene().name == "CommonScene" || SceneManager.GetActiveScene().name == "TitleScene" || SceneManager.GetActiveScene().name == "MapScene" || SceneManager.GetActiveScene().name == "") { SceneManager.LoadScene("CommonScene"); Debug.Log("Starting MAGIS from the title screen"); } } } else if (buildNotReady && loadedLevel != null) { // actually load the current editor level, and also load ARScene automatically if needed SceneManager.LoadScene(loadedLevel); SceneManager.LoadScene("ARScene", LoadSceneMode.Additive); loadedLevel = null; } } else if (!EditorApplication.isPlaying && !EditorApplication.isCompiling && !EditorApplication.isUpdating) { // automatically switch target to iOS or Android if the current target is Windows, macOS, etc. // (doing it here intentionally because we don't want to do it during Autorun constructor) if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iOS && EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android) { buildNotReady = true; if ((int)System.Environment.OSVersion.Platform == 4 || (int)System.Environment.OSVersion.Platform == 6) { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.iOS, BuildTarget.iOS); } else { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android); } return; } else { if (!EditorUserBuildSettings.GetBuildLocation(BuildTarget.iOS).EndsWith("ios_" + DeviceInput.GameName())) { EditorUserBuildSettings.development = true; } EditorUserBuildSettings.buildAppBundle = !EditorUserBuildSettings.development; EditorUserBuildSettings.SetBuildLocation(BuildTarget.iOS, "ios_" + DeviceInput.GameName()); if (EditorUserBuildSettings.buildAppBundle) { EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "aab_" + DeviceInput.GameName() + ".aab"); } else { EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "apk_" + DeviceInput.GameName() + ".apk"); } } // fix to remove empty .fbm folders that create spurious meta files // (doing it here intentionally because we don't want to do it during Autorun constructor) foreach (string asset in AssetDatabase.FindAssets(".fbm")) { string folder = AssetDatabase.GUIDToAssetPath(asset); if (AssetDatabase.IsValidFolder(folder)) { if (AssetDatabase.FindAssets("t:Object", new[] { folder }).Length == 0) { buildNotReady = true; Debug.Log("Deleting empty folder " + folder); AssetDatabase.DeleteAsset(folder); } } } // fix to remove extraneous _TerrainAutoUpgrade // (doing it here intentionally because we don't want to do it during Autorun constructor) if (AssetDatabase.IsValidFolder("Assets/_TerrainAutoUpgrade")) { buildNotReady = true; Debug.Log("Deleting migration folder _TerrainAutoUpgrade"); AssetDatabase.DeleteAsset("Assets/_TerrainAutoUpgrade"); } CleanUp(); } else { buildNotReady = true; } }
private void OnTablesGUI() { var settings = activeSettings.ActiveSettings; if (settings == null) { return; } if (!stylesLoaded) { LoadStyles(); } if (tableQueryChanged) { UpdateTableFilter(); tableQueryChanged = false; } GUILayout.BeginVertical(style_containerNoMarginTop); tableSearchScroll = GUILayout.BeginScrollView(tableSearchScroll, filteredTables.Count * 40 >= 200 ? new[] { GUILayout.MaxHeight(200), GUILayout.MinHeight(0) } : new GUILayoutOption[0]); selectedTable = GUILayoutExtras.Selection(selectedTable, filteredTables, (val, isSelected, index) => { var back = GUI.backgroundColor; GUI.backgroundColor = index % 2 == 0 ? new Color(0.8f, 0.8f, 0.8f) : Color.white; GUI.enabled = !isSelected; var clicked = GUILayout.Button("", style_localeSelectionEntryButton, GUILayout.MinHeight(40)); var lastRect = GUILayoutUtility.GetLastRect(); GUI.enabled = true; GUI.Label(lastRect, $"{val.TableName}", style_localeSelectionEntryLabel); GUI.backgroundColor = back; return(clicked); }); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.BeginHorizontal(style_containerNoMarginTop); if (GUILayout.Button("Open Table Editor", GUILayout.Height(30))) { TableEditorWindow.Display(settings); } if (selectedTable == null) { GUI.enabled = false; } if (GUILayout.Button("Remove Selected", GUILayout.Height(30))) { if (EditorUtility.DisplayDialog("Confirm table removal", "This action cannot be undone. Are you sure you want to delete the table?", "Yes", "No")) { settings.RemoveTable(selectedTable); AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(selectedTable)); Utils.SaveChanges(); selectedTable = null; Utils.DirtyTables(settings); } } GUI.enabled = true; GUILayout.EndHorizontal(); }
void CellGUI(Rect cellRect, TreeViewItem <QuestElement> item, MyColumns column, ref RowGUIArgs args) { // Center cell rect vertically (makes it easier to place controls, icons etc in the cells) CenterRectUsingSingleLineHeight(ref cellRect); switch (column) { //case MyColumns.Icon1: // { // //GUI.DrawTexture(cellRect, s_TestIcons[GetIcon1Index(item)], ScaleMode.ScaleToFit); // } // break; //case MyColumns.Icon2: // { // //GUI.DrawTexture(cellRect, s_TestIcons[GetIcon2Index(item)], ScaleMode.ScaleToFit); // } // break; case MyColumns.PrimaryKey: DefaultGUI.Label(cellRect, item.data.Pk.ToString(), args.selected, args.focused); break; case MyColumns.OpenAsset: { Rect buttonRect = cellRect; buttonRect.x += GetContentIndent(item); buttonRect.width = 25; if (GUI.Button(buttonRect, s_TestIcons[0])) { Selection.activeObject = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(item.data.Path); } } break; case MyColumns.Name: { // Do toggle //Rect toggleRect = cellRect; //toggleRect.x += GetContentIndent(item); //toggleRect.width = kToggleWidth; //if (toggleRect.xMax < cellRect.xMax) //item.data.enabled = EditorGUI.Toggle(toggleRect, item.data.enabled); // hide when outside cell rect // Default icon and label //args.rowRect = cellRect; //base.RowGUI(args); EditorGUI.LabelField(cellRect, item.data.name); } break; case MyColumns.Description: DefaultGUI.Label(cellRect, item.data.Description, args.selected, args.focused); break; case MyColumns.Objectives: DefaultGUI.Label(cellRect, item.data.Objectives, args.selected, args.focused); break; case MyColumns.Active: { Rect toggleRect = cellRect; toggleRect.x += GetContentIndent(item); toggleRect.width = kToggleWidth; EditorGUI.Toggle(toggleRect, item.data.Active); } break; case MyColumns.Complete: { Rect toggleRect = cellRect; toggleRect.x += GetContentIndent(item); toggleRect.width = kToggleWidth; EditorGUI.Toggle(toggleRect, item.data.Completed); } break; case MyColumns.Delete: { Rect buttonRect = cellRect; buttonRect.x += GetContentIndent(item); buttonRect.width = 55; if (GUI.Button(buttonRect, "Delete")) { int choice = EditorUtility.DisplayDialogComplex("Delete Quest?", $"Delete both the database entry and local asset OR just the database entry for '{item.data.name}'?", "DB Entry and Asset", "Cancel", "DB Entry Only"); if (choice == 1) { } else { var dbPath = $@"Assets/StreamingAssets/{"quests.db"}"; var connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create); connection.Delete <QuestEntry>(item.data.Pk); connection.Close(); if (choice == 0) // delete both { AssetDatabase.DeleteAsset(item.data.Path); } Repaint(); Debug.Log("Deleted"); } } } break; //case MyColumns.Value1: //case MyColumns.Value2: //case MyColumns.Value3: // { // if (showControls) // { // cellRect.xMin += 5f; // When showing controls make some extra spacing // if (column == MyColumns.Value1) // item.data.floatValue1 = EditorGUI.Slider(cellRect, GUIContent.none, item.data.floatValue1, 0f, 1f); // if (column == MyColumns.Value2) // item.data.material = (Material)EditorGUI.ObjectField(cellRect, GUIContent.none, item.data.material, typeof(Material), false); // if (column == MyColumns.Value3) // item.data.text = GUI.TextField(cellRect, item.data.text); // } // else // { // string value = "Missing"; // if (column == MyColumns.Value1) // value = item.data.floatValue1.ToString("f5"); // if (column == MyColumns.Value2) // value = item.data.floatValue2.ToString("f5"); // if (column == MyColumns.Value3) // value = item.data.floatValue3.ToString("f5"); // DefaultGUI.LabelRightAligned(cellRect, value, args.selected, args.focused); // } // } // break; default: throw new ArgumentOutOfRangeException(nameof(column), column, null); } }
/// <summary> /// Copy srcaar files to aar files that are excluded from Unity's build process. /// </summary> /// <param name="dependencies">Dependencies to inject.</param> /// <returns>true if successful, false otherwise.</returns> private static bool CopySrcAars(ICollection <Dependency> dependencies) { bool succeeded = true; var aarFiles = new List <KeyValuePair <string, string> >(); // Copy each .srcaar file to .aar while configuring the plugin importer to ignore the // file. foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) { // Only need to copy for .srcaar if (Path.GetExtension(aar).CompareTo(".srcaar") != 0) { continue; } var aarPath = aar; if (FileUtils.IsUnderPackageDirectory(aar)) { var logicalPackagePath = FileUtils.GetPackageDirectory(aar, FileUtils.PackageDirectoryType.AssetDatabasePath); aarPath = FileUtils.ReplaceBaseAssetsOrPackagesFolder( aar, logicalPackagePath); } var dir = FileUtils.ReplaceBaseAssetsOrPackagesFolder( Path.GetDirectoryName(aar), GooglePlayServices.SettingsDialog.LocalMavenRepoDir); var filename = Path.GetFileNameWithoutExtension(aarPath); var targetFilename = Path.Combine(dir, filename + ".aar"); bool configuredAar = File.Exists(targetFilename); if (!configuredAar) { var error = PlayServicesResolver.CopyAssetAndLabel( aarPath, targetFilename); if (String.IsNullOrEmpty(error)) { try { PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath( targetFilename); importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); configuredAar = true; } catch (Exception ex) { PlayServicesResolver.Log(String.Format( "Failed to disable {0} from being included by Unity's " + "internal build. {0} has been deleted and will not be " + "included in Gradle builds. ({1})", aar, ex), level: LogLevel.Error); } } else { PlayServicesResolver.Log(String.Format( "Unable to copy {0} to {1}. {1} will not be included in Gradle " + "builds. Reason: {2}", aarPath, targetFilename, error), level: LogLevel.Error); } } if (configuredAar) { aarFiles.Add(new KeyValuePair <string, string>(aarPath, targetFilename)); // Some versions of Unity do not mark the asset database as dirty when // plugin importer settings change so reimport the asset to synchronize // the state. AssetDatabase.ImportAsset(targetFilename, ImportAssetOptions.ForceUpdate); } else { if (File.Exists(targetFilename)) { AssetDatabase.DeleteAsset(targetFilename); } succeeded = false; } } foreach (var keyValue in aarFiles) { succeeded &= LocalMavenRepository.PatchPomFile(keyValue.Value, keyValue.Key); } return(succeeded); }
private static void CheckVersion() { EditorApplication.update -= CheckVersion; if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { string localVersion = NoesisVersion.GetCached(); string version = NoesisVersion.Get(); // Remove the file that indicates Noesis package is being installed AssetDatabase.DeleteAsset("Assets/NoesisGUI/Plugins/Editor/installing"); // Detect if /Library is being recreated string noesisFile = Path.Combine(Application.dataPath, "../Library/noesis"); bool libraryFolderRecreated = !File.Exists(noesisFile); if (libraryFolderRecreated) { File.Create(noesisFile).Dispose(); } if (localVersion != version && version != "0.0.0") { if (NoesisVersion.RestartNeeded()) { Debug.LogWarning("Please restart Unity to reload NoesisGUI native plugin! " + "If error persists remove 'Assets/NoesisGUI/Plugins' and reimport again."); return; } string title; if (localVersion != "") { title = "Upgrading NoesisGUI " + localVersion + " -> " + version; } else { title = "Installing NoesisGUI " + version; } EditorUtility.DisplayProgressBar(title, "", 0.0f); GoogleAnalyticsHelper.LogEvent("Install", version, 0); EditorUtility.DisplayProgressBar(title, "Upgrading project", 0.10f); Upgrade(localVersion); EditorUtility.DisplayProgressBar(title, "Updating version", 0.20f); NoesisVersion.SetCached(version); EditorUtility.DisplayProgressBar(title, "Creating default settings", 0.35f); NoesisSettings.Get(); EditorUtility.DisplayProgressBar(title, "Extracting documentation...", 0.40f); DeleteFolder("/../NoesisDoc"); ExtractTar("NoesisGUI/Doc.tar", "/../NoesisDoc"); EditorUtility.DisplayProgressBar(title, "Extracting blend samples...", 0.55f); DeleteFolder("/../Blend"); ExtractTar("NoesisGUI/Samples-blend.tar", "/.."); NoesisPostprocessor.ImportAllAssets((progress, asset) => { EditorUtility.DisplayProgressBar(title, asset, 0.60f + progress * 0.40f); }); EditorApplication.update += ShowWelcomeWindow; EditorUtility.ClearProgressBar(); Debug.Log("NoesisGUI v" + version + " successfully installed"); } else if (libraryFolderRecreated) { NoesisPostprocessor.ImportAllAssets(); } } }
/// <summary> /// Copy srcaar files to aar files that are excluded from Unity's build process. /// </summary> /// <param name="dependencies">Dependencies to inject.</param> /// <returns>true if successful, false otherwise.</returns> private static bool CopySrcAars(ICollection <Dependency> dependencies) { bool succeeded = true; var aarFiles = new List <string>(); // Copy each .srcaar file to .aar while configuring the plugin importer to ignore the // file. foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) { var dir = Path.GetDirectoryName(aar); var filename = Path.GetFileNameWithoutExtension(aar); var targetFilename = Path.Combine(dir, filename + ".aar"); bool configuredAar = File.Exists(targetFilename); if (!configuredAar) { bool copiedAndLabeledAar = AssetDatabase.CopyAsset(aar, targetFilename); if (copiedAndLabeledAar) { var unlabeledAssets = new HashSet <string>(); PlayServicesResolver.LabelAssets( new [] { targetFilename }, complete: (unlabeled) => { unlabeledAssets.UnionWith(unlabeled); }); copiedAndLabeledAar = unlabeledAssets.Count == 0; } if (copiedAndLabeledAar) { try { PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath( targetFilename); importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); configuredAar = true; } catch (Exception ex) { PlayServicesResolver.Log(String.Format( "Failed to disable {0} from being included by Unity's " + "internal build. {0} has been deleted and will not be " + "included in Gradle builds. ({1})", aar, ex), level: LogLevel.Error); } } else { PlayServicesResolver.Log(String.Format( "Unable to copy {0} to {1}. {1} will not be included in Gradle " + "builds.", aar, targetFilename), level: LogLevel.Error); } if (configuredAar) { aarFiles.Add(targetFilename); } else { if (File.Exists(targetFilename)) { AssetDatabase.DeleteAsset(targetFilename); } succeeded = false; } } } foreach (var aar in aarFiles) { if (!LocalMavenRepository.PatchPomFile(aar)) { succeeded = false; } } return(succeeded); }
static void CreateMyFont() { if (Selection.objects == null) { return; } if (Selection.objects.Length == 0) { Debug.LogWarning("没有选中fnt文件,或者图片文件"); return; } //至少需要保证选中文件的目录下面有fnt文件,否则不会生成字体 Font m_myFont = null; TextAsset m_data = null; string filePath = ""; Material mat = null; Texture2D tex = null; bool bln = false; //不管选中fnt、png、mat、fontsettings其中的任何一个,都可以创建字体 foreach (UnityEngine.Object o in Selection.objects) { if (o.GetType() == typeof(TextAsset)) { m_data = o as TextAsset; bln = true; } else if (o.GetType() == typeof(Material)) { mat = o as Material; bln = true; } else if (o.GetType() == typeof(Texture2D)) { tex = o as Texture2D; bln = true; } else if (o.GetType() == typeof(Font)) { m_myFont = o as Font; bln = true; } if (bln) { filePath = AssetDatabase.GetAssetPath(o); filePath = filePath.Substring(0, filePath.LastIndexOf('.')); } } //获取fnt文件,我们在这里加一次判断,为了可以直接选择图片也能导出字体 string dataPathName = filePath + ".fnt"; if (m_data == null) { m_data = (TextAsset)AssetDatabase.LoadAssetAtPath(dataPathName, typeof(TextAsset)); } if (m_data != null) { string matPathName = filePath + ".mat"; string fontPathName = filePath + ".fontsettings"; string texPathName = filePath + ".png"; //获取图片,如果没有图片,不影响,可以生成之后,再手动设置 if (tex == null) { tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texPathName, typeof(Texture2D)); } if (tex == null) { Debug.LogWarning("没找到图片,或者图片名称和fnt文件名称不匹配"); } //获取材质,如果没有则创建对应名字的材质 if (mat == null) { mat = (Material)AssetDatabase.LoadAssetAtPath(matPathName, typeof(Material)); } if (mat == null) { mat = new Material(Shader.Find("GUI/Text Shader")); AssetDatabase.CreateAsset(mat, matPathName); } else { mat.shader = Shader.Find("GUI/Text Shader"); } mat.SetTexture("_MainTex", tex); //获取font文件,如果没有则创建对应名字的font文件 if (m_myFont == null) { m_myFont = (Font)AssetDatabase.LoadAssetAtPath(fontPathName, typeof(Font)); } if (m_myFont == null) { m_myFont = new Font(); AssetDatabase.CreateAsset(m_myFont, fontPathName); } m_myFont.material = mat; BMFont mbFont = new BMFont(); //借助NGUI的类,读取字体fnt文件信息,可以不用自己去解析了 BMFontReader.Load(mbFont, m_data.name, m_data.bytes); CharacterInfo[] characterInfo = new CharacterInfo[mbFont.glyphs.Count]; for (int i = 0; i < mbFont.glyphs.Count; i++) { BMGlyph bmInfo = mbFont.glyphs[i]; CharacterInfo info = new CharacterInfo(); //设置ascii码 info.index = bmInfo.index; //设置字符映射到材质上的坐标 info.uvBottomLeft = new Vector2((float)bmInfo.x / mbFont.texWidth, 1f - (float)(bmInfo.y + bmInfo.height) / mbFont.texHeight); info.uvBottomRight = new Vector2((float)(bmInfo.x + bmInfo.width) / mbFont.texWidth, 1f - (float)(bmInfo.y + bmInfo.height) / mbFont.texHeight); info.uvTopLeft = new Vector2((float)bmInfo.x / mbFont.texWidth, 1f - (float)(bmInfo.y) / mbFont.texHeight); info.uvTopRight = new Vector2((float)(bmInfo.x + bmInfo.width) / mbFont.texWidth, 1f - (float)(bmInfo.y) / mbFont.texHeight); //设置字符顶点的偏移位置和宽高 info.minX = bmInfo.offsetX; info.minY = -bmInfo.offsetY - bmInfo.height; info.maxX = bmInfo.offsetX + bmInfo.width; info.maxY = -bmInfo.offsetY; //设置字符的宽度 info.advance = bmInfo.advance; characterInfo[i] = info; } m_myFont.characterInfo = characterInfo; EditorUtility.SetDirty(m_myFont); //设置变更过的资源 EditorUtility.SetDirty(mat); //设置变更过的资源 AssetDatabase.SaveAssets(); //保存变更的资源 AssetDatabase.Refresh(); //刷新资源,貌似在Mac上不起作用 //由于上面fresh之后在编辑器中依然没有刷新,所以暂时想到这个方法, //先把生成的字体导出成一个包,然后再重新导入进来,这样就可以直接刷新了 //这是在Mac上遇到的,不知道Windows下面会不会出现,如果不出现可以把下面这一步注释掉 AssetDatabase.ExportPackage(fontPathName, "temp.unitypackage"); AssetDatabase.DeleteAsset(fontPathName); AssetDatabase.ImportPackage("temp.unitypackage", true); AssetDatabase.Refresh(); Debug.Log("创建字体成功"); } else { Debug.LogWarning("没有找到fnt文件,或者文件名称和图片名称不匹配"); } }
public static void RebuildIndex() { AssetDatabase.DeleteAsset(indexPath); CreateIndex(); }
public void TearDown() { AssetDatabase.DeleteAsset(TempAssetDir); }
public void DeleteUnusedData() { foreach (tk2dSpriteCollectionFont font in obj.fonts) { bool found = false; foreach (tk2dSpriteCollectionFont f in fonts) { if (f.data == font.data && f.editorData == font.editorData) { found = true; break; } } if (!found) { tk2dEditorUtility.DeleteAsset(font.data); tk2dEditorUtility.DeleteAsset(font.editorData); } } if (obj.altMaterials != null) { foreach (Material material in obj.altMaterials) { bool found = false; if (altMaterials != null) { foreach (Material m in altMaterials) { if (m == material) { found = true; break; } } } if (!found) { tk2dEditorUtility.DeleteAsset(material); } } } List <tk2dSpriteCollectionPlatform> platformsToDelete = new List <tk2dSpriteCollectionPlatform>(); if (obj.HasPlatformData && !this.HasPlatformData) { platformsToDelete = new List <tk2dSpriteCollectionPlatform>(obj.platforms); atlasTextures = new Texture2D[0]; // clear all references atlasMaterials = new Material[0]; } else if (this.HasPlatformData && !obj.HasPlatformData) { // delete old sprite collection atlases and materials foreach (Material material in obj.atlasMaterials) { tk2dEditorUtility.DeleteAsset(material); } foreach (Texture2D texture in obj.atlasTextures) { tk2dEditorUtility.DeleteAsset(texture); } } else if (obj.HasPlatformData && this.HasPlatformData) { foreach (tk2dSpriteCollectionPlatform platform in obj.platforms) { bool found = false; foreach (tk2dSpriteCollectionPlatform p in platforms) { if (p.spriteCollection == platform.spriteCollection) { found = true; break; } } if (!found) // platform existed previously, but does not any more { platformsToDelete.Add(platform); } } } foreach (tk2dSpriteCollectionPlatform platform in platformsToDelete) { if (platform.spriteCollection == null) { continue; } tk2dSpriteCollection sc = platform.spriteCollection; string path = AssetDatabase.GetAssetPath(sc.spriteCollection); tk2dEditorUtility.DeleteAsset(sc.spriteCollection); foreach (Material material in sc.atlasMaterials) { tk2dEditorUtility.DeleteAsset(material); } foreach (Texture2D texture in sc.atlasTextures) { tk2dEditorUtility.DeleteAsset(texture); } foreach (tk2dSpriteCollectionFont font in sc.fonts) { tk2dEditorUtility.DeleteAsset(font.editorData); tk2dEditorUtility.DeleteAsset(font.data); } tk2dEditorUtility.DeleteAsset(sc); string dataDirName = System.IO.Path.GetDirectoryName(path); if (System.IO.Directory.Exists(dataDirName) && System.IO.Directory.GetFiles(dataDirName).Length == 0) { AssetDatabase.DeleteAsset(dataDirName); } } }
void ForgetUnsavedNavMeshDataChanges(PrefabStage prefabStage) { // Debug.Log("On prefab closing - forget about this object's surfaces and stop caring about prefab saving"); if (prefabStage == null) { return; } var allSurfacesInPrefab = prefabStage.prefabContentsRoot.GetComponentsInChildren <NavMeshSurface>(true); NavMeshSurface surfaceInPrefab = null; var index = 0; do { if (allSurfacesInPrefab.Length > 0) { surfaceInPrefab = allSurfacesInPrefab[index]; } for (var i = m_PrefabNavMeshDataAssets.Count - 1; i >= 0; i--) { var storedPrefabInfo = m_PrefabNavMeshDataAssets[i]; if (storedPrefabInfo.surface == null) { // Debug.LogFormat("A surface from the prefab got deleted after it has baked a new NavMesh but it hasn't saved it. Now the unsaved asset gets deleted. ({0})", storedPrefabInfo.navMeshData); // surface got deleted, thus delete its initial NavMeshData asset if (storedPrefabInfo.navMeshData != null) { var assetPath = AssetDatabase.GetAssetPath(storedPrefabInfo.navMeshData); AssetDatabase.DeleteAsset(assetPath); } m_PrefabNavMeshDataAssets.RemoveAt(i); } else if (surfaceInPrefab != null && storedPrefabInfo.surface == surfaceInPrefab) { //Debug.LogFormat("The surface {0} from the prefab was storing the original navmesh data and now will be forgotten", surfaceInPrefab); var baseSurface = PrefabUtility.GetCorrespondingObjectFromSource(surfaceInPrefab) as NavMeshSurface; if (baseSurface == null || surfaceInPrefab.navMeshData != baseSurface.navMeshData) { var assetPath = AssetDatabase.GetAssetPath(surfaceInPrefab.navMeshData); AssetDatabase.DeleteAsset(assetPath); //Debug.LogFormat("The surface {0} from the prefab has baked new NavMeshData but did not save this change so the asset has been now deleted. ({1})", // surfaceInPrefab, assetPath); } m_PrefabNavMeshDataAssets.RemoveAt(i); } } } while (++index < allSurfacesInPrefab.Length); if (m_PrefabNavMeshDataAssets.Count == 0) { PrefabStage.prefabSaving -= DeleteStoredNavMeshDataAssetsForOwnedSurfaces; PrefabStage.prefabStageClosing -= ForgetUnsavedNavMeshDataChanges; } }
private static void Upgrade_2_1_0_b10() { AssetDatabase.DeleteAsset("Assets/NoesisGUI/Samples/Common"); }
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { var vseWindows = (VseWindow[])Resources.FindObjectsOfTypeAll(typeof(VseWindow)); if (deletedAssets.Any()) { foreach (var deleted in deletedAssets) { if (Instance.m_ProjectAssetPaths.TryGetValue(deleted, out string path)) { foreach (var vseWindow in vseWindows) { vseWindow.UnloadGraphIfDeleted(); } // TODO : Fix for 1st drop. Find a better solution var graphName = Path.GetFileNameWithoutExtension(deleted); if (!string.IsNullOrEmpty(graphName)) { AssetDatabase.DeleteAsset(path); } } } } if (movedAssets.Any()) { for (var i = 0; i < movedAssets.Length; ++i) { var newAsset = movedAssets[i]; var oldAsset = movedFromAssetPaths[i]; if (Instance.m_ProjectAssetPaths.TryGetValue(oldAsset, out string path)) { foreach (var vseWindow in vseWindows) { vseWindow.UnloadGraphIfDeleted(); } // TODO : Fix for 1st drop. Find a better solution var newGraphName = Path.GetFileNameWithoutExtension(newAsset); var oldGraphName = Path.GetFileNameWithoutExtension(oldAsset); // if the Graph has been renamed, not just moved if (!string.IsNullOrEmpty(newGraphName) && newGraphName != oldGraphName) { AssetDatabase.DeleteAsset(path); var newAssetModel = AssetDatabase.LoadAssetAtPath <VSGraphAssetModel>(newAsset); newAssetModel.name = newGraphName; ((VSGraphModel)newAssetModel.GraphModel).name = newGraphName; foreach (var vseWindow in vseWindows.Where(w => w.CurrentGraphModel == newAssetModel.GraphModel)) { vseWindow.Store.Dispatch(new RefreshUIAction(UpdateFlags.All)); } } } } } var importedGraphAssets = importedAssets.Where(AssetAtPathIsVsGraphAsset).ToList(); foreach (var importedGraphAsset in importedGraphAssets) { var path = (AssetDatabase.LoadAssetAtPath <VSGraphAssetModel>(importedGraphAsset)?.GraphModel as VSGraphModel)?.SourceFilePath; if (path != null) { Instance.m_ProjectAssetPaths[importedGraphAsset] = path; } else { Instance.m_ProjectAssetPaths.Remove(importedGraphAsset); } } if (importedGraphAssets.Any()) { Version++; } }
private static void Upgrade_2_1_0_rc4() { AssetDatabase.DeleteAsset("Assets/NoesisGUI/Samples/TicTacToe"); }
public static void EnableNativeVideoPlayer() { // rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java if (File.Exists(disabledPlayerFileName)) { File.Move(disabledPlayerFileName, videoPlayerFileName); File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta"); } AssetDatabase.ImportAsset(videoPlayerFileName); AssetDatabase.DeleteAsset(disabledPlayerFileName); // Enable audio plugins PluginImporter audio360 = (PluginImporter)AssetImporter.GetAtPath(audio360PluginPath); PluginImporter audio360exo29 = (PluginImporter)AssetImporter.GetAtPath(audio360Exo29PluginPath); if (audio360 != null && audio360exo29 != null) { audio360.SetCompatibleWithPlatform(BuildTarget.Android, true); audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true); audio360.SaveAndReimport(); audio360exo29.SaveAndReimport(); } // Enable gradle build with exoplayer EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle; if (!File.Exists(gradleTemplatePath)) { if (File.Exists(gradleTemplatePath + ".DISABLED")) { File.Move(disabledGradleTemplatePath, gradleTemplatePath); File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath + ".meta"); } else { File.Copy(internalGradleTemplatePath, gradleTemplatePath); } AssetDatabase.ImportAsset(gradleTemplatePath); } // parse the gradle file to check the current version: string currentFile = File.ReadAllText(gradleTemplatePath); List <string> lines = new List <string>(currentFile.Split('\n')); var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value; if (gradleVersion == "2.3.0") { // add google() to buildscript/repositories int buildscriptRepositories = GoToSection("buildscript.repositories", lines); if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1) { lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()"); } // add google() and jcenter() to allprojects/repositories int allprojectsRepositories = GoToSection("allprojects.repositories", lines); if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1) { lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()"); } if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1) { lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()"); } } // add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies int dependencies = GoToSection("dependencies", lines); if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1) { lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'"); } int android = GoToSection("android", lines); // add compileOptions to add Java 1.8 compatibility if (FindInScope("compileOptions", android + 1, lines) == -1) { int compileOptionsIndex = GetScopeEnd(android + 1, lines); lines.Insert(compileOptionsIndex, "\t}"); lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8"); lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8"); lines.Insert(compileOptionsIndex, "\tcompileOptions {"); } // add sourceSets if Version < 2018.2 #if !UNITY_2018_2_OR_NEWER if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1) { lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\""); } #endif File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray())); }
public static void RemoveAndroidManifest() { AssetDatabase.DeleteAsset("Assets/Plugins/Android/AndroidManifest.xml"); AssetDatabase.Refresh(); }
public void Destoroy() { AssetDatabase.DeleteAsset("Assets/id_name"); AssetDatabase.DeleteAsset("Assets/TestTemplateLoad"); AssetDatabase.DeleteAsset("Assets/TestTemplateLoad2"); }
/// <summary> /// Rebuilds which files are master files and the connections between the files. /// </summary> public static void RebuildInkFileConnections() { Queue <InkFile> inkFileQueue = new Queue <InkFile>(instance.inkLibrary); while (inkFileQueue.Count > 0) { InkFile inkFile = inkFileQueue.Dequeue(); inkFile.parents = new List <DefaultAsset>(); inkFile.masterInkAssets = new List <DefaultAsset>(); inkFile.ParseContent(); inkFile.FindIncludedFiles(true); foreach (InkFile includedInkFile in inkFile.includesInkFiles) { if (!inkFileQueue.Contains(includedInkFile)) { inkFileQueue.Enqueue(includedInkFile); } } } // We now set the master file for ink files. As a file can be in an include hierarchy, we need to do this in two passes. // First, we set the master file to the file that includes an ink file. foreach (InkFile inkFile in instance.inkLibrary) { if (inkFile.includes.Count == 0) { continue; } foreach (InkFile otherInkFile in instance.inkLibrary) { if (inkFile == otherInkFile) { continue; } if (inkFile.includes.Contains(otherInkFile.inkAsset)) { if (!otherInkFile.parents.Contains(inkFile.inkAsset)) { otherInkFile.parents.Add(inkFile.inkAsset); } } } } // Next, we create a list of all the files owned by the actual master file, which we obtain by travelling up the parent tree from each file. Dictionary <InkFile, List <InkFile> > masterChildRelationships = new Dictionary <InkFile, List <InkFile> >(); foreach (InkFile inkFile in instance.inkLibrary) { foreach (var parentInkFile in inkFile.parentInkFiles) { InkFile lastMasterInkFile = parentInkFile; InkFile masterInkFile = parentInkFile; while (masterInkFile.parents.Count != 0) { // This shouldn't just pick first, but iterate the whole lot! // I didn't feel like writing a recursive algorithm until it's actually needed though - a file included by several parents is already a rare enough case! masterInkFile = masterInkFile.parentInkFiles.First(); lastMasterInkFile = masterInkFile; } if (lastMasterInkFile.parents.Count > 1) { Debug.LogError("The ink ownership tree has another master file that is not discovered! This is an oversight of the current implementation. If you requres this feature, please take a look at the comment in the code above - if you solve it let us know and we'll merge it in!"); } if (!masterChildRelationships.ContainsKey(masterInkFile)) { masterChildRelationships.Add(masterInkFile, new List <InkFile>()); } masterChildRelationships[masterInkFile].Add(inkFile); } // if(inkFile.parent == null) // continue; // InkFile parent = inkFile.parentInkFile; // while (parent.metaInfo.parent != null) { // parent = parent.metaInfo.parentInkFile; // } // if(!masterChildRelationships.ContainsKey(parent)) { // masterChildRelationships.Add(parent, new List<InkFile>()); // } // masterChildRelationships[parent].Add(inkFile); } // Finally, we set the master file of the children foreach (var inkFileRelationship in masterChildRelationships) { foreach (InkFile childInkFile in inkFileRelationship.Value) { if (!childInkFile.masterInkAssets.Contains(inkFileRelationship.Key.inkAsset)) { childInkFile.masterInkAssets.Add(inkFileRelationship.Key.inkAsset); } else { Debug.LogWarning("Child file already contained master file reference! This is weird!"); } if (InkSettings.instance.handleJSONFilesAutomatically && childInkFile.jsonAsset != null) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(childInkFile.jsonAsset)); childInkFile.jsonAsset = null; } } } }
protected override bool PerformClean() { bool result; if (MaintainerSettings.Cleaner.useTrashBin) { result = AssetDatabase.MoveAssetToTrash(assetDatabasePath); } else { switch (type) { case RecordType.EmptyFolder: { if (Directory.Exists(path)) { Directory.Delete(path, true); } break; } case RecordType.UnusedAsset: { if (File.Exists(path)) { File.Delete(path); } break; } case RecordType.Error: break; case RecordType.Other: break; default: throw new ArgumentOutOfRangeException(); } // removes corresponding .meta files AssetDatabase.DeleteAsset(assetDatabasePath); result = !(Directory.Exists(path) || File.Exists(path)); } if (!result) { Debug.LogWarning(Maintainer.LOG_PREFIX + ProjectCleaner.MODULE_NAME + " can't clean asset: " + beautyPath); } else { string directory = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory)) { string[] filesInDir = Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly); if (filesInDir.Length == 0) { Create(RecordType.EmptyFolder, directory).Clean(); } } } return(result); }
public static void GenerateTileMapPalette() { var basePath = Application.dataPath + "/Resources/Prefabs/"; var generatedFolder = Path.GetDirectoryName($"{ Application.dataPath }/Tilemaps/Palettes/Generated/"); if (generatedFolder != null) { Directory.CreateDirectory(generatedFolder); } foreach (var palette in _palettes) { var title = palette[0]; string subPath; string assetPath; string filePath; // Create palette asset var go = new GameObject(); go.AddComponent <Grid>(); var layerOne = new GameObject { name = "Layer1" }; layerOne.transform.SetParent(go.transform); var tilemap = layerOne.AddComponent <Tilemap>(); var tilemapRenderer = layerOne.AddComponent <TilemapRenderer>(); tilemapRenderer.enabled = false; var y = 0; for (var i = 1; i < palette.Length; i++) { var x = 0; var folder = palette[i]; var files = Directory.GetFiles(basePath + folder, "*.prefab", SearchOption.AllDirectories); foreach (var file in files) { var name = Path.GetFileNameWithoutExtension(file); subPath = $"Tilemaps/Resources/Tiles/Generated/{ title }/{ name }"; assetPath = $"Assets/{ subPath }"; filePath = $"{ Application.dataPath }/{ subPath }/{ name }.asset"; if (File.Exists(filePath)) { File.Delete(filePath); } // Build the tile var tile = TileBuilder.CreateTile <ObjectTile>(LayerType.Objects); var cast = AssetDatabase.LoadAssetAtPath(file.Substring(file.IndexOf("Assets", StringComparison.Ordinal) + 0), typeof(GameObject)) as GameObject; tile.Rotatable = false; tile.Offset = false; tile.Object = cast; tile.PreviewSprite = PreviewSpriteBuilder.GetSpriteWithoutSaving(cast); TileBuilder.CreateAsset(tile, name, assetPath); var pos = new Vector3Int(x, y, 0); tilemap.SetEditorPreviewTile(pos, tile); tilemap.SetTile(pos, tile); EditorUtility.SetDirty(tile); x++; } y--; } var paletteInstance = ScriptableObject.CreateInstance <GridPalette>(); paletteInstance.name = "Palette Settings"; subPath = $"/Tilemaps/Palettes/Generated/{ title }.prefab"; assetPath = $"Assets{ subPath }"; filePath = $"{ Application.dataPath }{ subPath }"; if (File.Exists(filePath)) { AssetDatabase.DeleteAsset(assetPath); AssetDatabase.SaveAssets(); } var prefab = PrefabUtility.SaveAsPrefabAsset(go, assetPath); AssetDatabase.AddObjectToAsset(paletteInstance, prefab); AssetDatabase.SaveAssets(); GameObject.DestroyImmediate(go); } }
static Autorun() { EditorApplication.update += Update; try { StreamReader reader = new StreamReader("Assets/ARGames/ARGameList.txt"); string[] rows = reader.ReadToEnd().Split('\n'); reader.Close(); for (int i = 0; i < rows.Length; i++) { // add product name to cloud id lookup if (rows[i].EndsWith("\r")) { rows[i] = rows[i].Substring(0, rows[i].Length - 1); } string[] cols = rows[i].Split(','); if (cols.Length > (int)ARGameList.CLOUD_PROJECT_ID) { productNameToCloudProjectId[cols[(int)ARGameList.PRODUCT_NAME]] = cols[(int)ARGameList.CLOUD_PROJECT_ID]; } } } catch (Exception) { singleGameProject = true; } foreach (KeyValuePair <string, string> entry in productNameToCloudProjectId) { // unhide resources folder of current game, hide resources folders of other games bool currentGame = (Application.productName == entry.Key); string folderName = Application.dataPath + "/ARGames/" + DeviceInput.NameToFolderName(entry.Key) + "/Resources"; System.Diagnostics.Process process = new System.Diagnostics.Process(); if ((int)System.Environment.OSVersion.Platform == 4 || (int)System.Environment.OSVersion.Platform == 6) { process.StartInfo.FileName = "chflags"; process.StartInfo.Arguments = (currentGame ? "nohidden \"" : "hidden \"") + folderName + "\""; } else { process.StartInfo.FileName = "attrib.exe"; process.StartInfo.Arguments = (currentGame ? "-h \"" : "+h \"") + folderName.Replace('/', '\\') + "\""; } process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); process.WaitForExit(); } // force recompile when switching from a different game if (AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now")) { AssetDatabase.DeleteAsset("Assets/_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now"); AssetDatabase.Refresh(); foreach (string asset in AssetDatabase.FindAssets("t:Script")) { string path = AssetDatabase.GUIDToAssetPath(asset); if (path.StartsWith("Assets/") && path != "Assets/AREngine/Editor/Autorun.cs") { AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); } } } AssetDatabase.Refresh(); CleanUp(); }
public void DestroyPrefabAssets() { AssetDatabase.DeleteAsset(m_TempFolderPath); }
//アトラス画像とデータを出力して、インポートするターゲットをリビルド static void RebuildTarget(AssetBuildTimeStamp buildTimeStamp, DicingTextures target, List <Atlas> atlasList) { List <string> outputTexturePathList = new List <string>(); List <DicingTextureData> textureDataList = new List <DicingTextureData>(); //アトラス画像をファイルとして出力 string dir = AssetDatabase.GetAssetPath(target.OutputDir); int count = 0; foreach (var atlas in atlasList) { ++count; Texture2D texture = atlas.MakeAtlasTexture(); string path = FilePathUtil.Combine(dir, atlas.Name + ".png"); outputTexturePathList.Add(path); atlas.Write(path, texture); Object.DestroyImmediate(texture); DisplayProgressBar(target, 0.7f + 0.2f * count / atlasList.Count, "Make AtlasTexture"); //元テクスチャを再現するための、頂点データやアトラス画像に対するUV値を作成 textureDataList.AddRange(atlas.MakeImportData()); DisplayProgressBar(target, 0.7f + 0.29f * count / atlasList.Count, "Make AtlasTexture"); } textureDataList.Sort((a, b) => string.Compare(a.Name, b.Name)); //新しいテクスチャをロード List <Texture2D> newTextureList = new List <Texture2D>(); foreach (var path in outputTexturePathList) { Texture2D texture = AssetDatabase.LoadAssetAtPath <Texture2D>(path); if (texture == null) { AssetDatabase.ImportAsset(path); texture = AssetDatabase.LoadAssetAtPath <Texture2D>(path); } newTextureList.Add(texture); } //登録済みのテクスチャのうち、使わなくなったものを削除 List <Texture2D> removeTextureList = new List <Texture2D>(); foreach (var texture in target.AtlasTextures) { if (!newTextureList.Contains(texture)) { removeTextureList.Add(texture); } } //テクスチャを設定 target.Build(buildTimeStamp, newTextureList, textureDataList); //インポート設定を上書き foreach (var path in outputTexturePathList) { AssetDatabase.ImportAsset(path); OverrideAtlasTextureImportSetting(path, target); } //使わなくなったものを削除 foreach (var texture in removeTextureList) { Debug.Log("Remove " + texture.name); AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(texture)); } }
private void createReorderableList() { editor = Editor.CreateEditor(Database.Instance); // Get Attributes listAttributes = new ReorderableList(editor.serializedObject, editor.serializedObject.FindProperty("attributes"), true, true, true, true); // Draw attributes listAttributes.drawElementCallback = (Rect rectL, int index, bool isActive, bool isFocused) => { var element = listAttributes.serializedProperty.GetArrayElementAtIndex(index); Attribute attribute = element.objectReferenceValue as Attribute; if (attribute != null) { var textDimensions = GUI.skin.label.CalcSize(new GUIContent(attribute.name)); rectL.y += 2; foldout[index] = EditorGUI.Foldout(new Rect(rectL.x, rectL.y, textDimensions.x + 5, rectL.height), foldout[index], attribute.name); if (GUI.Button(new Rect(rectL.width, rectL.y, 16, 16), new GUIContent("", removeTexture), removeStyle)) { Database.Instance.attributes.RemoveAt(index); } if (foldout[index]) { SerializedObject attr = new SerializedObject(attribute); rectL.height = EditorGUIUtility.singleLineHeight; rectL.x += 15; rectL.width -= 15; rectL.y += EditorGUIUtility.singleLineHeight; GUI.SetNextControlName("Name"); EditorGUI.PropertyField(rectL, attr.FindProperty("name")); rectL.y += EditorGUIUtility.singleLineHeight; EditorGUI.PropertyField(rectL, attr.FindProperty("id")); rectL.y += EditorGUIUtility.singleLineHeight; EditorGUI.PropertyField(rectL, attr.FindProperty("description")); rectL.y += EditorGUIUtility.singleLineHeight; EditorGUI.PropertyField(rectL, attr.FindProperty("isCore")); if (GUI.changed) { attr.ApplyModifiedProperties(); if (GUI.GetNameOfFocusedControl() != "Name") { AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(attribute), attribute.name + ".asset"); } } listAttributes.elementHeight = EditorGUIUtility.singleLineHeight * 5.0f + 4.0f; } else { listAttributes.elementHeight = EditorGUIUtility.singleLineHeight + 4.0f; } } }; listAttributes.elementHeightCallback += (idx) => { if (foldout[idx]) { return(EditorGUIUtility.singleLineHeight * 5.0f + 4.0f); } else { return(EditorGUIUtility.singleLineHeight + 4.0f); } }; // listAttributes header listAttributes.drawHeaderCallback = (Rect rectH) => { EditorGUI.LabelField(rectH, "Attributes List"); }; // Add attributes listAttributes.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => { Attribute attrb = CreateInstance <Attribute>(); attrb.name = "New Attribute " + Database.Instance.attributes.Count.ToString("D3"); attrb.id = "X" + Database.Instance.attributes.Count.ToString("D2"); Database.Instance.attributes.Add(attrb); foldout = Enumerable.Repeat(false, Database.Instance.attributes.Count).ToList(); var specializedClassesPath = "Assets/TRPGMaker/Database/Attributes"; var _exists = AssetDatabase.LoadAssetAtPath(specializedClassesPath + "/" + attrb.name + ".asset", typeof(SpecializedClass)); if (_exists == null) { //Create the folder if doesn't exist if (!System.IO.Directory.Exists(specializedClassesPath)) { System.IO.Directory.CreateDirectory(specializedClassesPath); } AssetDatabase.CreateAsset(attrb, specializedClassesPath + "/" + attrb.name + ".asset"); } }; // Detect attribute changed listAttributes.onChangedCallback = (ReorderableList l) => { foldout = Enumerable.Repeat(false, Database.Instance.attributes.Count).ToList(); }; // On remove attribute listAttributes.onRemoveCallback = (ReorderableList l) => { var attribute = l.serializedProperty.GetArrayElementAtIndex(l.index).objectReferenceValue as Attribute; Database.Instance.attributes.Remove(attribute); AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(attribute)); }; }
public void FullTeardown() { // Delete cloned sprites AssetDatabase.DeleteAsset(Path.GetDirectoryName(kTestTempFolder)); }
public static void Process() { // default Material for image visuals Material sourceMaterial = AssetDatabase.LoadAssetAtPath <Material> (materialPath); string json = File.ReadAllText(Application.dataPath + "/" + jsonPath); Imageframes imagesframes = JsonUtility.FromJson <Imageframes> (json); // if no container game object exists, make one var container = GameObject.Find(containerName); if (container == null) { container = new GameObject(containerName); } foreach (var imageframe in imagesframes.imageframe) { var filename = Path.GetFileName(imageframe.image_filepath); var srcPath = "Assets/_ARImages/" + filename; var dstPath = "Assets/_ARImages/" + imageframe.name + Path.GetExtension(imageframe.image_filepath); var asset = AssetDatabase.LoadAssetAtPath <Texture> (srcPath); if (asset == null) { Debug.LogWarning(srcPath + " doesn't exist"); continue; } var existingTexture = AssetDatabase.LoadAssetAtPath <Texture> (dstPath); if (existingTexture) { AssetDatabase.DeleteAsset(dstPath); Debug.LogWarning(dstPath + " already exists"); } var error = AssetDatabase.MoveAsset(srcPath, dstPath); if (!string.IsNullOrEmpty(error)) { Debug.LogError($"Error when renaming '{srcPath}' to '{dstPath}: {error}"); } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); foreach (var imageframe in imagesframes.imageframe) { Debug.Log( $"imageframe.centerpoint_x {imageframe.centerpoint_x} imageframe.centerpoint_y {imageframe.centerpoint_y}"); var center = new Vector3(imageframe.centerpoint_x, imageframe.centerpoint_y, imageframe.centerpoint_z); var vectorW = new Vector3(imageframe.vectorW_x, imageframe.vectorW_y, imageframe.vectorW_z); var vectorH = new Vector3(imageframe.vectorH_x, imageframe.vectorH_y, imageframe.vectorH_z); // var up = Vector3.Cross (vectorH, vectorW); var quadGameObject = new GameObject { name = imageframe.name }; quadGameObject .transform .SetParent(container.transform); var mesh = new Mesh(); /* * var matrix = * Matrix4x4.TRS ( * center, * Quaternion.identity, * new Vector3 ( * vectorW.magnitude, * 1f, * vectorH.magnitude)); * */ mesh.vertices = new[] { new Vector3(-0.5f, 0f, -0.5f), new Vector3(-0.5f, 0f, 0.5f), new Vector3(0.5f, 0f, 0.5f), new Vector3(0.5f, 0f, -0.5f) }; mesh.triangles = new[] { 0, 1, 3, 1, 2, 3 }; mesh.uv = new[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; mesh.RecalculateNormals(); var quadGameObjectTransform = quadGameObject.transform; quadGameObjectTransform.localPosition = center; quadGameObjectTransform.localRotation = Quaternion.FromToRotation(Vector3.right, vectorW) * Quaternion.FromToRotation(Vector3.forward, vectorH); // quadGameObjectTransform.localRotation = Quaternion.FromToRotation (Vector3.up, up); quadGameObjectTransform.localScale = new Vector3(vectorW.magnitude, 1f, vectorH.magnitude); var meshFilter = quadGameObject.AddComponent <MeshFilter> (); var meshRenderer = quadGameObject.AddComponent <MeshRenderer> (); var texturePath = "Assets/_ARImages/" + imageframe.name + Path.GetExtension(imageframe.image_filepath); var material = meshRenderer.material = new Material(sourceMaterial); var texture = AssetDatabase.LoadAssetAtPath <Texture> (texturePath); meshFilter.mesh = mesh; material.mainTexture = texture; quadGameObject.AddComponent <NcGameObjectInfo> (); var imageInfo = quadGameObject.AddComponent <NcafARImageInfo> (); var regex = new Regex("^([^_]+)_w([^_]+)_h([^_]+)___(.+)$"); var imageFrameName = imageframe.name; if (!regex.IsMatch(imageFrameName)) { Debug.LogError($"Unable to parse imageframe name {imageframe.name}"); continue; } var match = regex.Match(imageFrameName); var indexStr = match.Groups[1].Value; var widthStr = match.Groups[2].Value; var heightStr = match.Groups[3].Value; var name = match.Groups[4].Value; if (!int.TryParse(indexStr, out var index)) { Debug.LogError($"Unable to parse index from {imageFrameName}"); continue; } if (!float.TryParse(widthStr, out var width)) { Debug.LogError($"Unable to parse width from {imageFrameName}"); continue; } if (!float.TryParse(heightStr, out var height)) { Debug.LogError($"Unable to parse height from {imageFrameName}"); continue; } imageInfo.m_augmentedImageIndex = index; imageInfo.m_width = width; imageInfo.m_height = height; imageInfo.m_augmentedImageName = name; } }