ImportSampleMenu.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #if !UNITY_2019_1_OR_NEWER
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using UnityEditor;
  6. namespace Coffee.UIExtensions.Editors
  7. {
  8. internal static class ImportSampleMenu_UIUnmask
  9. {
  10. private const string k_DisplayName = "UI Unmask";
  11. private const string k_JsonGuid = "011faffdd04c64066883bc8402a48942";
  12. [MenuItem("Assets/Samples/" + k_DisplayName + "/Import Demo")]
  13. private static void ImportDemo()
  14. {
  15. ImportSample(k_JsonGuid, "Demo");
  16. }
  17. private static void ImportSample(string jsonGuid, string sampleName)
  18. {
  19. var jsonPath = AssetDatabase.GUIDToAssetPath(jsonGuid);
  20. var packageRoot = Path.GetDirectoryName(jsonPath).Replace('\\', '/');
  21. var json = File.ReadAllText(jsonPath);
  22. var version = Regex.Match(json, "\"version\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
  23. var src = string.Format("{0}/Samples~/{1}", packageRoot, sampleName);
  24. var dst = string.Format("Assets/Samples/{0}/{1}/{2}", k_DisplayName, version, sampleName);
  25. var previousPath = GetPreviousSamplePath(k_DisplayName, sampleName);
  26. // Remove the previous sample directory.
  27. if (!string.IsNullOrEmpty(previousPath))
  28. {
  29. var msg = "A different version of the sample is already imported at\n\n"
  30. + previousPath
  31. + "\n\nIt will be deleted when you update. Are you sure you want to continue?";
  32. if (!EditorUtility.DisplayDialog("Sample Importer", msg, "OK", "Cancel"))
  33. return;
  34. FileUtil.DeleteFileOrDirectory(previousPath);
  35. var metaFile = previousPath + ".meta";
  36. if (File.Exists(metaFile))
  37. FileUtil.DeleteFileOrDirectory(metaFile);
  38. }
  39. if (!Directory.Exists(dst))
  40. FileUtil.DeleteFileOrDirectory(dst);
  41. var dstDir = Path.GetDirectoryName(dst);
  42. if (!Directory.Exists(dstDir))
  43. Directory.CreateDirectory(dstDir);
  44. if (Directory.Exists(src))
  45. FileUtil.CopyFileOrDirectory(src, dst);
  46. else
  47. throw new DirectoryNotFoundException(src);
  48. AssetDatabase.Refresh(ImportAssetOptions.ImportRecursive);
  49. }
  50. private static string GetPreviousSamplePath(string displayName, string sampleName)
  51. {
  52. var sampleRoot = string.Format("Assets/Samples/{0}", displayName);
  53. var sampleRootInfo = new DirectoryInfo(sampleRoot);
  54. if (!sampleRootInfo.Exists) return null;
  55. return sampleRootInfo.GetDirectories()
  56. .Select(versionDir => Path.Combine(versionDir.ToString(), sampleName))
  57. .FirstOrDefault(Directory.Exists);
  58. }
  59. }
  60. }
  61. #endif