XRRGBCamera.cs 2.2 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 bool isAuto = true;
  9. public static XRRGBCamera Instance;
  10. public Texture CaptureImage;
  11. public WebCamTexture RGBCamTexture;
  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 (this.GetComponent<RawImage>() != null)
  25. {
  26. this.GetComponent<RawImage>().color = Color.black;
  27. }
  28. if (this.GetComponent<MeshRenderer>() != null)
  29. {
  30. this.GetComponent<MeshRenderer>().color = Color.black;
  31. }
  32. return;
  33. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  34. {
  35. RGBCamTexture.Stop();
  36. }
  37. // 将WebCamTexture绑定到RawImage组件以显示摄像头捕捉到的图像
  38. WebCamDevice[] devices = WebCamTexture.devices;
  39. if (devices.Length == 0)
  40. {
  41. Debug.Log("No webcam devices found.");
  42. return;
  43. }
  44. // 使用第一个可用的摄像头设备(你可以根据需要选择其他设备)
  45. RGBCamTexture = new WebCamTexture(devices[0].name, w, h, 30);
  46. Debug.Log("开启摄像头" + devices[0].name);
  47. // 开始摄像头捕捉
  48. RGBCamTexture.Play();
  49. CaptureImage = RGBCamTexture;
  50. if (this.GetComponent<RawImage>() != null)
  51. {
  52. this.GetComponent<RawImage>().texture = CaptureImage;
  53. this.GetComponent<RawImage>().transform.localEulerAngles = new Vector3(0, 0, 0);
  54. }
  55. if (this.GetComponent<MeshRenderer>() != null)
  56. {
  57. this.GetComponent<MeshRenderer>().material.mainTexture = CaptureImage;
  58. this.GetComponent<MeshRenderer>().transform.localEulerAngles = new Vector3(0, 0, 0);
  59. }
  60. Debug.Log("开启摄像头");
  61. }
  62. public void Update()
  63. {
  64. }
  65. public void stopCamera()
  66. {
  67. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  68. {
  69. RGBCamTexture.Stop();
  70. }
  71. }
  72. }