DefaultCompileChecker.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #if UNITY_2019_1_OR_NEWER
  2. using System;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using UnityEditor;
  6. using UnityEditor.Compilation;
  7. using UnityEngine;
  8. namespace SingularityGroup.HotReload.Editor {
  9. class DefaultCompileChecker : ICompileChecker {
  10. const string recompileFilePath = PackageConst.LibraryCachePath + "/recompile.txt";
  11. public bool hasCompileErrors { get; private set; }
  12. bool recompile;
  13. public DefaultCompileChecker() {
  14. CompilationPipeline.assemblyCompilationFinished += DetectCompileErrors;
  15. CompilationPipeline.compilationFinished += OnCompilationFinished;
  16. var currentSessionId = EditorAnalyticsSessionInfo.id;
  17. Task.Run(() => {
  18. try {
  19. var compileSessionId = File.ReadAllText(recompileFilePath);
  20. if(compileSessionId == currentSessionId.ToString()) {
  21. ThreadUtility.RunOnMainThread(() => {
  22. recompile = true;
  23. _onCompilationFinished?.Invoke();
  24. });
  25. }
  26. File.Delete(recompileFilePath);
  27. } catch(DirectoryNotFoundException) {
  28. //dir doesn't exist -> no recompile required
  29. } catch(FileNotFoundException) {
  30. //file doesn't exist -> no recompile required
  31. } catch(Exception ex) {
  32. Log.Warning("compile checker encountered issue: {0} {1}", ex.GetType().Name, ex.Message);
  33. }
  34. });
  35. }
  36. void DetectCompileErrors(string _, CompilerMessage[] messages) {
  37. for (int i = 0; i < messages.Length; i++) {
  38. if (messages[i].type == CompilerMessageType.Error) {
  39. hasCompileErrors = true;
  40. return;
  41. }
  42. }
  43. hasCompileErrors = false;
  44. }
  45. void OnCompilationFinished(object _) {
  46. //Don't recompile on compile errors
  47. if(!hasCompileErrors) {
  48. Directory.CreateDirectory(Path.GetDirectoryName(recompileFilePath));
  49. File.WriteAllText(recompileFilePath, EditorAnalyticsSessionInfo.id.ToString());
  50. }
  51. }
  52. Action _onCompilationFinished;
  53. public event Action onCompilationFinished {
  54. add {
  55. if(recompile && value != null) {
  56. value();
  57. }
  58. _onCompilationFinished += value;
  59. }
  60. remove {
  61. _onCompilationFinished -= value;
  62. }
  63. }
  64. }
  65. }
  66. #endif