XRRGBCamera.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. private void Awake()
  12. {
  13. Instance = this;
  14. }
  15. private void Start()
  16. {
  17. // 获取可用的摄像头设备
  18. playCamera();
  19. }
  20. public void playCamera()
  21. {
  22. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  23. {
  24. RGBCamTexture.Stop();
  25. }
  26. // 将WebCamTexture绑定到RawImage组件以显示摄像头捕捉到的图像
  27. WebCamDevice[] devices = WebCamTexture.devices;
  28. if (devices.Length == 0)
  29. {
  30. Debug.Log("No webcam devices found.");
  31. return;
  32. }
  33. // 使用第一个可用的摄像头设备(你可以根据需要选择其他设备)
  34. RGBCamTexture = new WebCamTexture(devices[0].name, 1280, 720, 30);
  35. Debug.Log("开启摄像头" + devices[0].name);
  36. // 开始摄像头捕捉
  37. RGBCamTexture.Play();
  38. CaptureImage = RGBCamTexture;
  39. if (this.GetComponent<RawImage>() != null)
  40. {
  41. this.GetComponent<RawImage>().texture = CaptureImage;
  42. this.GetComponent<RawImage>().transform.localEulerAngles = new Vector3(0, 0, 0);
  43. }
  44. if (this.GetComponent<MeshRenderer>() != null)
  45. {
  46. this.GetComponent<MeshRenderer>().material.mainTexture = CaptureImage;
  47. this.GetComponent<MeshRenderer>().transform.localEulerAngles = new Vector3(0, 0, 0);
  48. }
  49. Debug.Log("开启摄像头");
  50. }
  51. public void Update()
  52. {
  53. }
  54. public void stopCamera()
  55. {
  56. if (RGBCamTexture != null && RGBCamTexture.isPlaying)
  57. {
  58. RGBCamTexture.Stop();
  59. }
  60. }
  61. }