Unity调用USB摄像头开启与关闭

using UnityEngine;

public class WebCamera : MonoBehaviour {
    [Tooltip("返回的照片数据,根据返回的照片,进行照片的识别和比对认证等等!"), Space(5)]
    [Header("摄像头拍摄的照片"),]
    public WebCamTexture camTexture;//摄像头拍下的图片数据

    [Header("摄像头设备名")]
    private WebCamDevice[] devices;

    [Tooltip("USB摄像头设备"), Space(5)]
    [Header("摄像头设备名")]
    public string deviceName;//摄像头设备名称
   
    public bool isClick;//是否点击了按钮

    private void Start()
    {
        isClick = false;
    }
    //初始化摄像头显示的图像的大小
    private void Awake()
    {
        camTexture = new WebCamTexture(deviceName, 800, 600, 60);
    }

    //通过GUI绘制摄像头要显示的窗口
    private void OnGUI()
    {
        //首先根据摄像头展示的画面来判断摄像头是否存在
        if(isClick == true&&camTexture != null)
        {
           
            //绘制画面(Screen.width / 2 - 150f, Screen.height / 2 - 290,这里是画面距离场景的高和宽的限制)
            //800, 600是和camTexture的画面一样大的绘制窗口
            GUI.DrawTexture(new Rect(Screen.width / 2 - 150f, Screen.height / 2 - 290, 800, 600), camTexture);
        }
        if(isClick == false && camTexture != null)//不显示画面(没写这个步骤之前有个坑)
        {
            
            GUI.DrawTexture(new Rect(Screen.width / 2 - 150f, Screen.height / 2 - 290, 0, 0), camTexture);
        }

    }

    //打开摄像机的方法//挂到button按钮上
    public void OpenWebCamDevice()
    {
        isClick = true;
        if(isClick == true)
        {
            //用户授权打开摄像头
            if (Application.HasUserAuthorization(UserAuthorization.WebCam))
            {
                devices = WebCamTexture.devices;//显示画面的设备就是要打开的摄像头
                deviceName = devices[0].name;//获取到设备名称
                camTexture.Play();//开启摄像头
            }
        }
    }

    //关闭摄像头//挂到button按钮上
    public void CloseWebCamDevice()
    {
        if(isClick== true && camTexture != null)
        {
            isClick = false;
            
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38962400/article/details/79613102