openCamera.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class openCamera : MonoBehaviour
  6. {
  7. [HideInInspector]
  8. public WebCamTexture webTex;
  9. [HideInInspector]
  10. public string deviceName;
  11. public static openCamera Instance;
  12. private static List<GameObject> mats=new List<GameObject>();
  13. void Start()
  14. {
  15. if (Instance!=null)
  16. {
  17. webTex = openCamera.Instance.webTex;
  18. setTexture(this.gameObject, webTex);
  19. mats.Add(this.gameObject);
  20. }
  21. else
  22. {
  23. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  24. Instance = this;
  25. mats.Add(this.gameObject);
  26. StartCoroutine(CallCamera());
  27. }
  28. }
  29. public void setTexture(GameObject go,Texture tx)
  30. {
  31. MeshRenderer mr = go.GetComponent<MeshRenderer>();
  32. RawImage raw = go.GetComponent<RawImage>();
  33. if(mr ==null)
  34. {
  35. raw.texture = tx;
  36. }
  37. else
  38. {
  39. mr.material.mainTexture = tx;
  40. }
  41. }
  42. public void restart(int fps=30)
  43. {
  44. CustomInfo.FPS = fps;
  45. StartCoroutine(CallCamera());
  46. }
  47. void Update()
  48. {
  49. } ///
  50. ///调用摄像头
  51. ///
  52. IEnumerator CallCamera()
  53. {
  54. yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
  55. if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  56. {
  57. WebCamDevice[] devices = WebCamTexture.devices;
  58. deviceName = devices[0].name;
  59. if (webTex != null)
  60. {
  61. webTex.Stop();
  62. webTex = null;
  63. }
  64. //设置摄像机摄像的区域
  65. webTex = new WebCamTexture(deviceName, 1920,1440, CustomInfo.FPS);
  66. for (int i = 0; i < mats.Count; i++)
  67. {
  68. setTexture(mats[i], webTex);
  69. }
  70. webTex.Play();//开始摄像
  71. }
  72. }
  73. }