Unity调用摄像头功能简单实现方法

Unity调用摄像头功能简单实现方法

前言

在之前的公司做过很多调用摄像头功能的软件,如雀巢CEO合影软件(这个是比较成功的一个案例)。Unity调用摄像头比较容易实现,在这里做一个简单的记录。

步骤

1.写核心脚本功能,代码如下所示:

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

public class Tset : MonoBehaviour {

    //摄像头图像类,继承自texture
    WebCamTexture tex;
    public MeshRenderer ma;
    public Button saveImage;
    public bool isCamera = false;
    public string deviceName;
    string mPath = null;

    void Start()
    {
        //开启协程,获取摄像头图像数据
        StartCoroutine(OpenCamera());
    }
    IEnumerator OpenCamera()
    {
        //等待用户允许访问
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        //如果用户允许访问,开始获取图像        
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            //先获取设备
            WebCamDevice[] device = WebCamTexture.devices;
            deviceName = device[0].name;
            //然后获取图像
            tex = new WebCamTexture(deviceName,1920,1080,50);
            //将获取的图像赋值
            ma.material.mainTexture = tex;
            //开始实施获取
            tex.Play();
        }
    }
}

2.在场景中创建一个plane物体,将脚本挂载到此物体上,将Camera对准此物体,如下图所示:
在这里插入图片描述
3.运行工程,发现程序已经成功调用了摄像头,如下图所示:
在这里插入图片描述


版权声明:本文为qq_17367039原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。