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();
        }
    }

}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM