WaitForDomainReload.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections;
  3. using UnityEditor;
  4. using UnityEditorInternal;
  5. namespace UnityEngine.TestTools
  6. {
  7. /// <summary>
  8. /// WaitForDomainReload is an <see cref="IEditModeTestYieldInstruction"/> that you can yield in Edit Mode tests. It delays the execution of scripts until after an incoming domain reload. If the domain reload results in a script compilation failure, then it throws an exception.
  9. /// </summary>
  10. public class WaitForDomainReload : IEditModeTestYieldInstruction
  11. {
  12. /// <summary>
  13. /// Create a new instance of the `WaitForDomainReload` yield instruction.
  14. /// <example>
  15. /// <code>
  16. /// [UnitySetUp]
  17. /// public IEnumerator SetUp()
  18. /// {
  19. /// File.Copy("Resources/MyDll.dll", @"Assets/MyDll.dll", true); // Trigger a domain reload.
  20. /// AssetDatabase.Refresh();
  21. /// yield return new WaitForDomainReload();
  22. /// }
  23. /// </code>
  24. /// </example>
  25. /// </summary>
  26. public WaitForDomainReload()
  27. {
  28. ExpectDomainReload = true;
  29. }
  30. /// <summary>
  31. /// Returns true if the instruction expects a domain reload to occur.
  32. /// </summary>
  33. public bool ExpectDomainReload { get;  }
  34. /// <summary>
  35. /// Returns true if the instruction expects the Unity Editor to be in **Play Mode**.
  36. /// </summary>
  37. public bool ExpectedPlaymodeState { get; }
  38. /// <summary>
  39. /// Perform the multi step action of waiting for a domain reload.
  40. /// </summary>
  41. /// <returns>An IEnumerator with steps.</returns>
  42. /// <exception cref="Exception">Throws an exception if script compilation failed or if the expected domain reload did not occur.</exception>
  43. public IEnumerator Perform()
  44. {
  45. EditorApplication.UnlockReloadAssemblies();
  46. while (InternalEditorUtility.IsScriptReloadRequested() || EditorApplication.isCompiling)
  47. {
  48. yield return null;
  49. }
  50. // Add this point the domain reload should have occured and stopped any further progress on the instruction.
  51. EditorApplication.LockReloadAssemblies();
  52. throw new Exception(
  53. EditorUtility.scriptCompilationFailed ?
  54. "Script compilation failed" :
  55. "Expected domain reload, but it did not occur");
  56. }
  57. }
  58. }