ColorSourceManager.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using UnityEngine;
  2. using System.Collections;
  3. using Windows.Kinect;
  4. public class ColorSourceManager : MonoBehaviour
  5. {
  6. public int ColorWidth { get; private set; }
  7. public int ColorHeight { get; private set; }
  8. private KinectSensor _Sensor;
  9. private ColorFrameReader _Reader;
  10. private Texture2D _Texture;
  11. private byte[] _Data;
  12. public Texture2D GetColorTexture()
  13. {
  14. return _Texture;
  15. }
  16. void Start()
  17. {
  18. _Sensor = KinectSensor.GetDefault();
  19. if (_Sensor != null)
  20. {
  21. _Reader = _Sensor.ColorFrameSource.OpenReader();
  22. var frameDesc = _Sensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba);
  23. ColorWidth = frameDesc.Width;
  24. ColorHeight = frameDesc.Height;
  25. _Texture = new Texture2D(frameDesc.Width, frameDesc.Height, TextureFormat.RGBA32, false);
  26. _Data = new byte[frameDesc.BytesPerPixel * frameDesc.LengthInPixels];
  27. if (!_Sensor.IsOpen)
  28. {
  29. _Sensor.Open();
  30. }
  31. }
  32. }
  33. void Update ()
  34. {
  35. if (_Reader != null)
  36. {
  37. var frame = _Reader.AcquireLatestFrame();
  38. if (frame != null)
  39. {
  40. frame.CopyConvertedFrameDataToArray(_Data, ColorImageFormat.Rgba);
  41. _Texture.LoadRawTextureData(_Data);
  42. _Texture.Apply();
  43. frame.Dispose();
  44. frame = null;
  45. }
  46. }
  47. }
  48. void OnApplicationQuit()
  49. {
  50. if (_Reader != null)
  51. {
  52. _Reader.Dispose();
  53. _Reader = null;
  54. }
  55. if (_Sensor != null)
  56. {
  57. if (_Sensor.IsOpen)
  58. {
  59. _Sensor.Close();
  60. }
  61. _Sensor = null;
  62. }
  63. }
  64. }