NRKernalUpdater.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using UnityEngine;
  12. using System;
  13. /// <summary> Used to drive the lifecycle. </summary>
  14. [ScriptOrder(NativeConstants.NRKERNALUPDATER_ORDER)]
  15. public class NRKernalUpdater : MonoBehaviour
  16. {
  17. /// <summary> The instance. </summary>
  18. private static NRKernalUpdater m_Instance;
  19. /// <summary> Gets the instance. </summary>
  20. /// <value> The instance. </value>
  21. public static NRKernalUpdater Instance
  22. {
  23. get
  24. {
  25. if (m_Instance == null && !m_IsDestroyed)
  26. {
  27. m_Instance = CreateInstance();
  28. }
  29. return m_Instance;
  30. }
  31. }
  32. [RuntimeInitializeOnLoadMethod]
  33. static void Initialize()
  34. {
  35. if (m_Instance == null)
  36. {
  37. m_Instance = CreateInstance();
  38. }
  39. }
  40. /// <summary> Creates the instance. </summary>
  41. /// <returns> The new instance. </returns>
  42. private static NRKernalUpdater CreateInstance()
  43. {
  44. GameObject updateObj = new GameObject("NRKernalUpdater");
  45. GameObject.DontDestroyOnLoad(updateObj);
  46. return updateObj.AddComponent<NRKernalUpdater>();
  47. }
  48. /// <summary> Event queue for all listeners interested in OnPreUpdate events. </summary>
  49. public static event Action OnPreUpdate;
  50. /// <summary> Event queue for all listeners interested in OnUpdate events. </summary>
  51. public static event Action OnUpdate;
  52. /// <summary> Event queue for all listeners interested in OnPostUpdate events. </summary>
  53. public static event Action OnPostUpdate;
  54. #if DEBUG_PERFORMANCE
  55. long lastFrame = 0;
  56. #endif
  57. /// <summary> Updates this object. </summary>
  58. private void Update()
  59. {
  60. #if DEBUG_PERFORMANCE
  61. long curFrame = System.DateTime.Now.Ticks;
  62. long duration = curFrame - lastFrame;
  63. #endif
  64. OnPreUpdate?.Invoke();
  65. OnUpdate?.Invoke();
  66. OnPostUpdate?.Invoke();
  67. #if DEBUG_PERFORMANCE
  68. long curFrameEnd = System.DateTime.Now.Ticks;
  69. long curFrameDur = curFrameEnd - curFrame;
  70. NRDebugger.Info("[Performance] Main update: frameAll={0}Tick, frameUpdate={1}", duration, curFrameDur);
  71. lastFrame = curFrame;
  72. #endif
  73. }
  74. private static bool m_IsDestroyed = false;
  75. private void OnDestroy()
  76. {
  77. m_Instance = null;
  78. m_IsDestroyed = true;
  79. }
  80. }
  81. }