你的位置:首页 > 操作系统

[操作系统]Unity调用外部摄像头,全屏显示摄像头画面


有两种方法,常用的是GUI方法,代码如下:

public class CameraTest : MonoBehaviour {  WebCamTexture camTexture;  void Start () {    StartCoroutine(CallCamera());  }  IEnumerator CallCamera()  {    yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);    if (Application.HasUserAuthorization(UserAuthorization.WebCam))    {      if (camTexture != null)        camTexture.Stop();      WebCamDevice[] cameraDevices = WebCamTexture.devices;      string deviceName = cameraDevices[0].name;      Debug.Log(deviceName);      camTexture = new WebCamTexture(deviceName);      camTexture.Play();    }  }  void OnGUI()  {    if(camTexture!=null)    {      GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), camTexture, ScaleMode.StretchToFill);    }  }}

  

GUI已经被抛弃,效率,DrawCall,适配等各种差,现使用UGUI实现:

public class CameraTest : MonoBehaviour {  WebCamTexture camTexture;  Image img;  public GameObject quad;  void Start () {    img = GetComponentInChildren<Image>();    StartCoroutine(CallCamera());  }  IEnumerator CallCamera()  {    yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);    if (Application.HasUserAuthorization(UserAuthorization.WebCam))    {      if (camTexture != null)        camTexture.Stop();      WebCamDevice[] cameraDevices = WebCamTexture.devices;      string deviceName = cameraDevices[0].name;      Debug.Log(deviceName);      camTexture = new WebCamTexture(deviceName);      img.canvasRenderer.SetTexture(camTexture); //注意改行代码      camTexture.Play();    }  }}