Unity 3d UI获取外部摄像头拍摄

Unity 3d UI获取外部摄像头拍摄

3D环境下调用外部摄像头的方法网络上有很多,在此不过多说,本方法是在2D环境下利用UI来调用外部摄像头进行拍摄,总体而言,两种环境下所用到的核心方法是一样的。

1、创建一个RawImagin,并命名为CameraPlay

在这里插入图片描述

2、创建一个脚本,命名为PlaneManager,将脚本随便挂在一个物体上。脚本中的public RawImage rawImage;要记得在Inspector面板中把CameraPlay添上去

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlaneManager : MonoBehaviour
{
    public string DeviceName;
    //public Vector2 CameraSize;
    public float CameraFPS;

    //接收返回的图片数据  
    WebCamTexture _webCamera;
    //public GameObject Plane;//作为显示摄像头的面板
    public RawImage rawImage;


    void OnGUI()
    {
        if (GUI.Button(new Rect(100, 100, 100, 100), "Initialize Camera"))
        {
            StartCoroutine("InitCameraCor");
        }

        //添加一个按钮来控制摄像机的开和关
        if (GUI.Button(new Rect(100, 250, 100, 100), "ON/OFF"))
        {
            if (_webCamera != null && rawImage != null)
            {

                if (_webCamera.isPlaying)
                    StopCamera();
                else
                    PlayCamera();
            }
        }
        if (GUI.Button(new Rect(100, 450, 100, 100), "Quit"))
        {

            Application.Quit();
        }

    }

    public void PlayCamera()
    {
        //Plane.GetComponent<MeshRenderer>().enabled = true;
        rawImage.enabled = true;
        _webCamera.Play();
    }


    public void StopCamera()
    {
        // Plane.GetComponent<MeshRenderer>().enabled = false;
        rawImage.enabled = false;
        _webCamera.Stop();
    }

    /// <summary>  
    /// 初始化摄像头
    /// </summary>  
    public IEnumerator InitCameraCor()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            DeviceName = devices[0].name;
            _webCamera = new WebCamTexture(DeviceName, 1920, 1080, 60);

            rawImage.texture = _webCamera;
            //Plane.GetComponent<Renderer>().material.mainTexture = _webCamera;
            //Plane.transform.localScale = new Vector3(1, 1, 1);

            _webCamera.Play();
            //前置后置摄像头需要旋转一定角度,否则画面是不正确的,必须置于Play()函数后
            rawImage.rectTransform.localEulerAngles = new Vector3(0, 0,_webCamera.videoRotationAngle+360);
        }
    }
}

3、运行结果

在这里插入图片描述

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值