XRRGBCamera.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using SC.XR.Unity;
  6. public class XRRGBCamera : SingletonMono<XRRGBCamera>
  7. {
  8. public static XRRGBCamera Instance;
  9. public Texture CaptureImage;
  10. public WebCamTexture RGBCamTexture;
  11. public bool isAuto = true;
  12. private void Awake()
  13. {
  14. Instance = this;
  15. }
  16. private void Start()
  17. {
  18. // 获取可用的摄像头设备
  19. if(isAuto)
  20. playCamera(1280,720);
  21. }
  22. public void playCamera(int w, int h)
  23. {
  24. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  25. {
  26. RGBCamTexture.Stop();
  27. }
  28. // 将WebCamTexture绑定到RawImage组件以显示摄像头捕捉到的图像
  29. WebCamDevice[] devices = WebCamTexture.devices;
  30. if (devices.Length == 0)
  31. {
  32. Debug.Log("No webcam devices found.");
  33. return;
  34. }
  35. #if UNITY_EDITOR
  36. // 使用第一个可用的摄像头设备(你可以根据需要选择其他设备)
  37. RGBCamTexture = new WebCamTexture(devices[0].name, w, h, 30);
  38. Debug.Log("开启摄像头" + devices[0].name);
  39. #else
  40. // 使用第一个可用的摄像头设备(你可以根据需要选择其他设备)
  41. RGBCamTexture = new WebCamTexture(devices[2].name, w, h, 30);
  42. Debug.Log("开启摄像头" + devices[2].name);
  43. #endif
  44. // 开始摄像头捕捉
  45. RGBCamTexture.Play();
  46. CaptureImage = RGBCamTexture;
  47. if (this.GetComponent<RawImage>() != null)
  48. {
  49. this.GetComponent<RawImage>().texture = CaptureImage;
  50. this.GetComponent<RawImage>().transform.localEulerAngles = new Vector3(0, 0, 0);
  51. }
  52. if (this.GetComponent<MeshRenderer>() != null)
  53. {
  54. this.GetComponent<MeshRenderer>().material.mainTexture = CaptureImage;
  55. this.GetComponent<MeshRenderer>().transform.localEulerAngles = new Vector3(0, 0, 0);
  56. }
  57. Debug.Log("开启摄像头");
  58. }
  59. public void Update()
  60. {
  61. }
  62. public void stopCamera()
  63. {
  64. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  65. {
  66. RGBCamTexture.Stop();
  67. }
  68. }
  69. }