AsyncTriggerExtensions.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  2. using System.Threading;
  3. using UnityEngine;
  4. using Cysharp.Threading.Tasks.Triggers;
  5. namespace Cysharp.Threading.Tasks
  6. {
  7. public static class UniTaskCancellationExtensions
  8. {
  9. /// <summary>This CancellationToken is canceled when the MonoBehaviour will be destroyed.</summary>
  10. public static CancellationToken GetCancellationTokenOnDestroy(this GameObject gameObject)
  11. {
  12. return gameObject.GetAsyncDestroyTrigger().CancellationToken;
  13. }
  14. /// <summary>This CancellationToken is canceled when the MonoBehaviour will be destroyed.</summary>
  15. public static CancellationToken GetCancellationTokenOnDestroy(this Component component)
  16. {
  17. return component.GetAsyncDestroyTrigger().CancellationToken;
  18. }
  19. }
  20. }
  21. namespace Cysharp.Threading.Tasks.Triggers
  22. {
  23. public static partial class AsyncTriggerExtensions
  24. {
  25. // Util.
  26. static T GetOrAddComponent<T>(GameObject gameObject)
  27. where T : Component
  28. {
  29. #if UNITY_2019_2_OR_NEWER
  30. if (!gameObject.TryGetComponent<T>(out var component))
  31. {
  32. component = gameObject.AddComponent<T>();
  33. }
  34. #else
  35. var component = gameObject.GetComponent<T>();
  36. if (component == null)
  37. {
  38. component = gameObject.AddComponent<T>();
  39. }
  40. #endif
  41. return component;
  42. }
  43. // Special for single operation.
  44. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  45. public static UniTask OnDestroyAsync(this GameObject gameObject)
  46. {
  47. return gameObject.GetAsyncDestroyTrigger().OnDestroyAsync();
  48. }
  49. /// <summary>This function is called when the MonoBehaviour will be destroyed.</summary>
  50. public static UniTask OnDestroyAsync(this Component component)
  51. {
  52. return component.GetAsyncDestroyTrigger().OnDestroyAsync();
  53. }
  54. public static UniTask StartAsync(this GameObject gameObject)
  55. {
  56. return gameObject.GetAsyncStartTrigger().StartAsync();
  57. }
  58. public static UniTask StartAsync(this Component component)
  59. {
  60. return component.GetAsyncStartTrigger().StartAsync();
  61. }
  62. public static UniTask AwakeAsync(this GameObject gameObject)
  63. {
  64. return gameObject.GetAsyncAwakeTrigger().AwakeAsync();
  65. }
  66. public static UniTask AwakeAsync(this Component component)
  67. {
  68. return component.GetAsyncAwakeTrigger().AwakeAsync();
  69. }
  70. }
  71. }