PlaneManager.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class PlaneManager : MonoBehaviour
  6. {
  7. public string DeviceName;
  8. //public Vector2 CameraSize;
  9. public float CameraFPS;
  10. //接收返回的图片数据
  11. WebCamTexture _webCamera;
  12. //public GameObject Plane;//作为显示摄像头的面板
  13. public RawImage rawImage;
  14. void OnGUI()
  15. {
  16. if (GUI.Button(new Rect(100, 100, 100, 100), "Initialize Camera"))
  17. {
  18. StartCoroutine("InitCameraCor");
  19. }
  20. //添加一个按钮来控制摄像机的开和关
  21. if (GUI.Button(new Rect(100, 250, 100, 100), "ON/OFF"))
  22. {
  23. if (_webCamera != null && rawImage != null)
  24. {
  25. if (_webCamera.isPlaying)
  26. StopCamera();
  27. else
  28. PlayCamera();
  29. }
  30. }
  31. if (GUI.Button(new Rect(100, 450, 100, 100), "Quit"))
  32. {
  33. Application.Quit();
  34. }
  35. }
  36. public void PlayCamera()
  37. {
  38. //Plane.GetComponent<MeshRenderer>().enabled = true;
  39. rawImage.enabled = true;
  40. _webCamera.Play();
  41. }
  42. public void StopCamera()
  43. {
  44. // Plane.GetComponent<MeshRenderer>().enabled = false;
  45. rawImage.enabled = false;
  46. _webCamera.Stop();
  47. }
  48. /// <summary>
  49. /// 初始化摄像头
  50. /// </summary>
  51. public IEnumerator InitCameraCor()
  52. {
  53. yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
  54. if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  55. {
  56. WebCamDevice[] devices = WebCamTexture.devices;
  57. DeviceName = devices[0].name;
  58. _webCamera = new WebCamTexture(DeviceName, 1920, 1080, 60);
  59. rawImage.texture = _webCamera;
  60. //Plane.GetComponent<Renderer>().material.mainTexture = _webCamera;
  61. //Plane.transform.localScale = new Vector3(1, 1, 1);
  62. _webCamera.Play();
  63. //前置后置摄像头需要旋转一定角度,否则画面是不正确的,必须置于Play()函数后
  64. rawImage.rectTransform.localEulerAngles = new Vector3(0, 0, _webCamera.videoRotationAngle + 360);
  65. }
  66. }
  67. }