序言
在学习Unity开发AR过程中,发现无论是Vuforia还是Unity中的ARkit或者ARcore,均是建立一个ARcamera,而这个camera是受他们AR内核支配的,并不是最原始的可控摄像头,所以萌生了想要做一个受自己控制的摄像头。实现这个愿望的第一步就是将摄像头的视频内容接入到Unity中,这篇文章就是讲的这个内容。
目标
- Unity可以打开摄像头并在窗口中显示
- 如果有多个摄像头,则可以通过按钮进行切换
unity中的实现
-
首先创建一个3D项目
-
在Hierarchy中创建一个Canvas(画布),在Game窗口中可以设定Canvas大小,目标设定为(1280*820)。
-
画布中创建以下子项目
RawImage(Raw Image)->用于显示摄像头的内容,大小为1280*720,并将RawImage与Canvas上边缘对齐。
CameraOnButton (button)->用于开启和关闭摄像头,点击第一次时是打开,点击第二次时为关闭。
CameraSwitchButton (button)->用于切换摄像头。
BG_Im(Image)->用于放在Canvas底部作为UI的背景使用,颜色调成深灰色。
创建好后如下所示:
-
创建一个空对象(Empty Object),取名为CameraController, 在CameraController下创建新脚本取名“CameraContrller”,脚本内容如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CameraContrller : MonoBehaviour
{
int currentCamIndex = 0;
WebCamTexture tex;
public RawImage display;
public Text startStopText;
public void SwapCam_Clicked()
{
if (WebCamTexture.devices.Length > 0 )//WebCamTexture.devices.Length表示接入电脑的摄像机数量,当摄像机数量大于0时,运行下面切换操作。
{
currentCamIndex += 1;
currentCamIndex %= WebCamTexture.devices.Length;//这行代码很有学习价值,它的意思是说设定一个数,计数器未达到这个数时,可以增加,当计数器达到这个数时会被重置为0
}
}
public void StartStopCam_Clicked()
{
if(tex != null)//stop camera
{
StopWebCam();
startStopText.text = "Start Camera";
}
else//start camera
{
WebCamDevice device = WebCamTexture.devices[currentCamIndex];
tex = new WebCamTexture(device.name);//根据设备名称创建一个新的WebCamTexture的类,并赋值给tex,此时tex已经包含了摄像头的视频信号。
display.texture = tex;//将摄像头的视频信号传递给RawImage中进行画面显示。
tex.Play();//播放
startStopText.text = "Stop Camera";
}
}
private void StopWebCam()
{
display.texture = null;
tex.Stop();
tex = null;
}
}
接下来,需要将RawImage和CameraOnButton中的Text赋值给CameraController中,并将CameraController赋值给CameraOnButton和CameaSwitchButton中,分别引用各自的函数,如下图:
CameraOnButton:
CameraSwitchButton:
以上内容建立好后,运行即可。