MonoBehaviourStartExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. namespace Rokid.UXR.Interaction
  2. {
  3. using System;
  4. using UnityEngine;
  5. /// <summary>
  6. /// By adding BeginStart and EndStart at the beginning and end of Start, MonoBehaviours with
  7. /// OnEnable and OnDisable logic can wrap their contents within a _started flag and effectively
  8. /// skip over logic in those methods until after Start has been invoked.
  9. ///
  10. /// To not bypass the Unity Lifecycle, the enabled property is used to disable the most derived
  11. /// MonoBehaviour, invoke Start up the hierarchy chain, and finally re-enable the MonoBehaviour.
  12. /// </summary>
  13. public static class MonoBehaviourStartExtensions
  14. {
  15. public static void BeginStart(this MonoBehaviour monoBehaviour, ref bool started,
  16. Action baseStart = null)
  17. {
  18. if (!started)
  19. {
  20. monoBehaviour.enabled = false;
  21. started = true;
  22. baseStart?.Invoke();
  23. started = false;
  24. }
  25. else
  26. {
  27. baseStart?.Invoke();
  28. }
  29. }
  30. public static void EndStart(this MonoBehaviour monoBehaviour, ref bool started)
  31. {
  32. if (!started)
  33. {
  34. started = true;
  35. monoBehaviour.enabled = true;
  36. }
  37. }
  38. }
  39. }