ImportSampleMenu.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.UIEffects
  7. {
  8. public static class ImportSampleMenu
  9. {
  10. private const string jsonGuid = "546af75b6221c4768be79d67c9cea1fb";
  11. [MenuItem("Assets/Samples/UIEffect/Import Demo")]
  12. private static void ImportDemo()
  13. {
  14. ImportSample(jsonGuid, "Demo");
  15. }
  16. private static void ImportSample(string jsonGuid, string sampleName)
  17. {
  18. var jsonPath = AssetDatabase.GUIDToAssetPath(jsonGuid);
  19. var json = File.ReadAllText(jsonPath);
  20. var version = Regex.Match(json, "\"version\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
  21. var displayName = Regex.Match(json, "\"displayName\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
  22. var src = string.Format("{0}/Samples~/{1}", Path.GetDirectoryName(jsonPath), sampleName);
  23. var srcAlt = string.Format("{0}/Samples/{1}", Path.GetDirectoryName(jsonPath), sampleName);
  24. var dst = string.Format("Assets/Samples/{0}/{1}/{2}", displayName, version, sampleName);
  25. var previousPath = GetPreviousSamplePath(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 if (Directory.Exists(srcAlt))
  47. FileUtil.CopyFileOrDirectory(srcAlt, dst);
  48. else
  49. throw new DirectoryNotFoundException(src);
  50. AssetDatabase.Refresh(ImportAssetOptions.ImportRecursive);
  51. }
  52. private static string GetPreviousSamplePath(string displayName, string sampleName)
  53. {
  54. var sampleRoot = string.Format("Assets/Samples/{0}", displayName);
  55. var sampleRootInfo = new DirectoryInfo(sampleRoot);
  56. if (!sampleRootInfo.Exists) return null;
  57. return sampleRootInfo.GetDirectories()
  58. .Select(versionDir => Path.Combine(versionDir.ToString(), sampleName))
  59. .FirstOrDefault(Directory.Exists);
  60. }
  61. }
  62. }
  63. #endif