EventPump.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Linq;
  5. namespace Helper
  6. {
  7. internal class EventPump : UnityEngine.MonoBehaviour
  8. {
  9. private static object s_Lock = new object();
  10. private Queue<Action> m_Queue = new Queue<Action>();
  11. public static EventPump Instance
  12. {
  13. get;
  14. private set;
  15. }
  16. public static void EnsureInitialized()
  17. {
  18. try
  19. {
  20. if (EventPump.Instance == null)
  21. {
  22. lock (s_Lock)
  23. {
  24. if (EventPump.Instance == null)
  25. {
  26. UnityEngine.GameObject parent = new UnityEngine.GameObject("Kinect Desktop Event Pump");
  27. EventPump.Instance = parent.AddComponent<Helper.EventPump>();
  28. DontDestroyOnLoad(parent);
  29. }
  30. }
  31. }
  32. }
  33. catch
  34. {
  35. UnityEngine.Debug.LogError("Events must be registered on the main thread.");
  36. return;
  37. }
  38. }
  39. private void Update()
  40. {
  41. lock (m_Queue)
  42. {
  43. while (m_Queue.Count > 0)
  44. {
  45. var action = m_Queue.Dequeue();
  46. try
  47. {
  48. action.Invoke();
  49. }
  50. catch { }
  51. }
  52. }
  53. }
  54. private void OnApplicationQuit()
  55. {
  56. var sensor = Windows.Kinect.KinectSensor.GetDefault();
  57. if (sensor != null && sensor.IsOpen)
  58. {
  59. sensor.Close();
  60. }
  61. NativeObjectCache.Flush();
  62. }
  63. public void Enqueue(Action action)
  64. {
  65. lock (m_Queue)
  66. {
  67. m_Queue.Enqueue(action);
  68. }
  69. }
  70. }
  71. }