实现思路:
unity封装好了一个 WebCamTexture 类,构造一个类的实例,然后调用 Play 函数。就能实时的获取摄像头的画面了。
构造一个完整的WebCamTexture,可以设置的参数有 摄像头的设备名、画面尺寸、刷新率。
当然构造函数的参数也可以为空,由于摄像头的设备可能有多个,这时候会默认使用第一个,画面尺寸和刷新率将使用最接近的可用值。
代码:
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public RawImage showImage;
private WebCamTexture webCamTexture;
void Start()
{
int deviceCount = WebCamTexture.devices.Length;
if (deviceCount != 0)
{
print("有" + deviceCount.ToString() + "个摄像头设备!");
webCamTexture = new WebCamTexture();
webCamTexture.Play();
showImage.texture = webCamTexture;//使用UGUI的RawImage显示出来画面
}
else
{
Debug.LogError("没有摄像头设备!");
}
}
}