HotReloadSettingsEditor.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.IO;
  2. using UnityEditor;
  3. using UnityEngine;
  4. namespace SingularityGroup.HotReload.Editor {
  5. static class HotReloadSettingsEditor {
  6. /// Ensure settings asset file is created and saved
  7. public static void EnsureSettingsCreated(HotReloadSettingsObject asset) {
  8. if (!SettingsExists()) {
  9. CreateNewSettingsFile(asset, HotReloadSettingsObject.editorAssetPath);
  10. }
  11. }
  12. /// Load existing settings asset or return the default settings
  13. public static HotReloadSettingsObject LoadSettingsOrDefault() {
  14. if (SettingsExists()) {
  15. return AssetDatabase.LoadAssetAtPath<HotReloadSettingsObject>(HotReloadSettingsObject.editorAssetPath);
  16. } else {
  17. // create an instance with default values
  18. return ScriptableObject.CreateInstance<HotReloadSettingsObject>();
  19. }
  20. }
  21. /// <summary>
  22. /// Create settings asset file
  23. /// </summary>
  24. /// <remarks>Assume that settings asset doesn't exist yet</remarks>
  25. /// <returns>The settings asset</returns>
  26. static void CreateNewSettingsFile(HotReloadSettingsObject asset, string editorAssetPath) {
  27. // create new settings asset
  28. // ReSharper disable once AssignNullToNotNullAttribute
  29. Directory.CreateDirectory(Path.GetDirectoryName(editorAssetPath));
  30. if (asset == null) {
  31. asset = ScriptableObject.CreateInstance<HotReloadSettingsObject>();
  32. }
  33. AssetDatabase.CreateAsset(asset, editorAssetPath);
  34. // Saving the asset isn't needed right after you created it. Unity will save it at the appropriate time.
  35. // Troy: I tested in Unity 2018 LTS, first Android build creates the asset file and asset is included in the build.
  36. }
  37. #region include/exclude in build
  38. private static bool SettingsExists() {
  39. return AssetExists(HotReloadSettingsObject.editorAssetPath);
  40. }
  41. private static bool AssetExists(string assetPath) {
  42. return AssetDatabase.GetMainAssetTypeAtPath(assetPath) != null;
  43. }
  44. public static void AddOrRemoveFromBuild(bool includeSettingsInBuild) {
  45. AssetDatabase.StartAssetEditing();
  46. var so = LoadSettingsOrDefault();
  47. try {
  48. if (includeSettingsInBuild) {
  49. // Note: don't need to force create settings because we know the defaults in player.
  50. so.EnsurePrefabSetCorrectly();
  51. EnsureSettingsCreated(so);
  52. } else {
  53. // this block shouldn't create the asset file, but it's also fine if it does
  54. so.EnsurePrefabNotInBuild();
  55. }
  56. } finally {
  57. AssetDatabase.StopAssetEditing();
  58. }
  59. }
  60. #endregion
  61. }
  62. }