【Unity3D-01】记录Unity3D调用外接摄像头
最近想在Unity3D上调用一个摄像头,通过查找资料发现仙魁XAN和八哥快走开的博客符合我的想法,实现起来也不难就尝试了一下
01 新建一个Unity3D的工程
02 开干!
2.1 在这个工程里新建Canvas
如下图所示
然后下设RawImage为载体
2.2 在Assets里面新建一个脚本命名为PlaneManager.cs
代码内容如下(参考八哥快走开的博客)
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, 30);
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);
}
}
}
2.3 把这个CS脚本挂到RawImage这个载体上(左键拖动.cs文件到RawImage)
2.4 记得把"Plane Manager"这个面板里的"Raw Image"选择RawImage(RawImage),否则会报错,无法出现摄像头的画面
如下图所示文章来源:https://www.toymoban.com/news/detail-767664.html
2.5 效果呈现
文章来源地址https://www.toymoban.com/news/detail-767664.html
到了这里,关于【Unity3D-01】 记录Unity3D调用外接摄像头的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!