今天为大家分享一下,如何通过WebCamera 调用外部的摄像头。 1.首先我们需要简单认识一下,unity有关摄像头需要用到的内置类; WebCamDevice 官方文档:https://docs.unity3d.com/ScriptReference/WebCamDevice.html WebCamTexture 官方文档:https://docs.unity3d.com/ScriptReference/WebCamTexture.html 2.新建一个unity3d 项目,在场景中新建Resources文件夹》Material文件夹,在文件夹中新建一个材质CameraPlane.mat;并且材质球的Shader:Unlit/Texture. ![]() 3.在场景中新建一个Camera,并且把对象重新命名为WebCamera,在WebCamera下面添加一个子对象Plane[PlaneMeshRender],注意点是:(1).plane的Rotation (X:90 Y:180 Z:0)如果不修改 ,显示的画面,会相反显示;(2).需要MeshRender,把第一步操作的材质球附加上。 4.到这一步,就是比较重点了,在WebCamera上附加一个WebCameraManager.cs 组件类,主要是处理调用外部摄像头,并且显示摄像的内容。 WebCameraManager.cs 代码如下:? using System.Collections;using System.Collections.Generic;
using UnityEngine;
public class WebCameraManager : MonoBehaviour {
public string DeviceName;
public Vector2 CameraSize;
public float CameraFPS;
//接收返回的图片数据
WebCamTexture _webCamera;
public GameObject Plane;//作为显示摄像头的面板
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 && Plane != 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;
_webCamera.Play();
}
public void StopCamera()
{
Plane.GetComponent<MeshRenderer> ().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,(int)CameraSize.x,(int)CameraSize.y,(int)CameraFPS);
Plane.GetComponent<Renderer> ().material.mainTexture=_webCamera;
Plane.transform.localScale = new Vector3 (1,1,1);
_webCamera.Play();
}
}
}
5.最后直接运行看效果哈! ![]()
![]()
来源:http://forum.china.unity3d.com/forum.php?mod=viewthread&tid=22870&extra=page%3D1%26filter%3Dauthor%26orderby%3Ddateline
|