WebCamManager.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace LonginesYogaPhotoJoy
  6. {
  7. public class WebCamManager : MonoBehaviour
  8. {
  9. public static WebCamManager Instance;
  10. public RawImage WebCamRawImage;
  11. private WebCamTexture webCamTexture;
  12. // private string deviceName = "Logitech BRIO";
  13. // private string deviceName = "Camera (NVIDIA Broadcast)";
  14. private string deviceName = "EOS Webcam Utility";
  15. // private string deviceName = "OBS Virtual Camera";
  16. private bool isReady = false;
  17. // ==================================================
  18. private void Awake()
  19. {
  20. Instance = this;
  21. }
  22. private void Start()
  23. {
  24. InitWebcam();
  25. // SwitchWebcam(true);
  26. }
  27. private void OnApplicationQuit()
  28. {
  29. SwitchWebcam(false);
  30. }
  31. // ==================================================
  32. // private void Init()
  33. // {
  34. // InitWebcam();
  35. // return;
  36. // }
  37. private void InitWebcam()
  38. {
  39. if (WebCamTexture.devices.Length <= 0)
  40. {
  41. Debug.Log("<color=red>[WM]</color> 无可用设备");
  42. return;
  43. }
  44. WebCamDevice[] devices = WebCamTexture.devices;
  45. for (int i = 0; i < devices.Length; i++)
  46. {
  47. Debug.Log($"[WM] 设备[{i}]:{devices[i].name}");
  48. if (devices[i].name == deviceName)
  49. {
  50. webCamTexture = new WebCamTexture(devices[i].name, Screen.width, Screen.height, 30)
  51. {
  52. wrapMode = TextureWrapMode.Clamp
  53. };
  54. WebCamRawImage.texture = webCamTexture;
  55. isReady = true;
  56. break;
  57. }
  58. }
  59. return;
  60. }
  61. public void SwitchWebcam(bool value)
  62. {
  63. if (webCamTexture == null || isReady == false)
  64. {
  65. return;
  66. }
  67. if (value == true)
  68. {
  69. webCamTexture.Play();
  70. }
  71. else
  72. {
  73. if (webCamTexture.isPlaying)
  74. {
  75. webCamTexture.Stop();
  76. }
  77. }
  78. return;
  79. }
  80. }
  81. }