XRRGBCamera.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 (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. // 使用第一个可用的摄像头设备(你可以根据需要选择其他设备)
  36. RGBCamTexture = new WebCamTexture(devices[0].name, w, h, 30);
  37. Debug.Log("开启摄像头" + devices[0].name);
  38. // 开始摄像头捕捉
  39. RGBCamTexture.Play();
  40. CaptureImage = RGBCamTexture;
  41. if (this.GetComponent<RawImage>() != null)
  42. {
  43. this.GetComponent<RawImage>().texture = CaptureImage;
  44. this.GetComponent<RawImage>().transform.localEulerAngles = new Vector3(0, 0, 0);
  45. }
  46. if (this.GetComponent<MeshRenderer>() != null)
  47. {
  48. this.GetComponent<MeshRenderer>().material.mainTexture = CaptureImage;
  49. this.GetComponent<MeshRenderer>().transform.localEulerAngles = new Vector3(0, 0, 0);
  50. }
  51. Debug.Log("开启摄像头");
  52. }
  53. public void Update()
  54. {
  55. }
  56. public void stopCamera()
  57. {
  58. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  59. {
  60. RGBCamTexture.Stop();
  61. }
  62. }
  63. }