CameraTest.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using System.Runtime.InteropServices;
  6. public class CameraTest : MonoBehaviour
  7. {
  8. [DllImport("__Internal")]
  9. private static extern void noCamera(string str);
  10. //public RawImage rawImage;//相机渲染的UI
  11. public GameObject quad;//相机渲染的GameObject
  12. private WebCamTexture webCamTexture;
  13. void Start()
  14. {
  15. //ToOpenCamera();
  16. }
  17. /// <summary>
  18. /// 打开摄像机
  19. /// </summary>
  20. public void ToOpenCamera()
  21. {
  22. StartCoroutine("OpenCamera");
  23. }
  24. public IEnumerator OpenCamera()
  25. {
  26. int maxl = Screen.width;
  27. if (Screen.height > Screen.width)
  28. {
  29. maxl = Screen.height;
  30. }
  31. // 申请摄像头权限
  32. yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
  33. if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  34. {
  35. if (webCamTexture != null)
  36. {
  37. webCamTexture.Stop();
  38. }
  39. //打开渲染图
  40. /*if (rawImage != null)
  41. {
  42. rawImage.gameObject.SetActive(true);
  43. }*/
  44. if (quad != null)
  45. {
  46. quad.gameObject.SetActive(true);
  47. }
  48. // 监控第一次授权,是否获得到设备(因为很可能第一次授权了,但是获得不到设备,这里这样避免)
  49. // 多次 都没有获得设备,可能就是真没有摄像头,结束获取 camera
  50. /*int i = 0;
  51. while (WebCamTexture.devices.Length <= 0 && 1 < 300)
  52. {
  53. yield return new WaitForEndOfFrame();
  54. i++;
  55. }*/
  56. WebCamDevice[] devices = WebCamTexture.devices;//获取可用设备
  57. if (WebCamTexture.devices.Length <= 0)
  58. {
  59. noCamera("没有摄像头设备,请检查");
  60. //Debug.LogError("没有摄像头设备,请检查");
  61. }
  62. else
  63. {
  64. string devicename = devices[0].name;
  65. webCamTexture = new WebCamTexture(devicename, maxl, maxl == Screen.height ? Screen.width : Screen.height, 30)
  66. {
  67. wrapMode = TextureWrapMode.Repeat
  68. };
  69. // 渲染到 UI 或者 游戏物体上
  70. /* if (rawImage != null)
  71. {
  72. rawImage.texture = webCamTexture;
  73. }*/
  74. if (quad != null)
  75. {
  76. quad.GetComponent<Renderer>().material.mainTexture = webCamTexture;
  77. }
  78. webCamTexture.Play();
  79. }
  80. }
  81. else
  82. {
  83. noCamera("未获得读取摄像头权限");
  84. //Debug.LogError("未获得读取摄像头权限");
  85. }
  86. }
  87. private void OnApplicationPause(bool pause)
  88. {
  89. // 应用暂停的时候暂停camera,继续的时候继续使用
  90. if (webCamTexture != null)
  91. {
  92. if (pause)
  93. {
  94. webCamTexture.Pause();
  95. }
  96. else
  97. {
  98. webCamTexture.Play();
  99. }
  100. }
  101. }
  102. private void OnDestroy()
  103. {
  104. if (webCamTexture != null)
  105. {
  106. webCamTexture.Stop();
  107. }
  108. }
  109. }