Unity 基础 之 WebCamTexture 获取设备摄像头(包括PC和移动端),简单渲染到 UGUI 或 游戏物体上
一、简单介绍
Unity中的一些基础知识点。
本节介绍,使用 WebCamTexture 获取设别的摄像头,并且进行渲染,同时解决有可能第一次授权却没有显示画面的情况。
二、实现原理
1、WebCamTexture 获取 WebCamDevice 设备
2、new WebCamTexture(WebCamDevice , width, height, fps) 得到目标摄像头的数据画面
3、渲染到 UGUI 或者 游戏物体上
三、注意事项
1、应用要申请 Camera 权限
2、为了避免第一次授权可能没有得到摄像头的画面的结果,添加安全设置多次未获得摄像头就,可能真没有设备,结束后获取摄像头
四、效果预览

五、实现步骤
1、打开 Unity,新建工程
2、布局场景,添加UGUI 和 游戏物体元素,用来摄像头画面渲染
3、在工程中添加脚本,并编辑脚本,实现获得摄像头画面渲染到画布或游戏物体上的功能
4、把脚本添加到场景中,并对应赋值
5、运行场景,效果如上
六、关键代码
1、OpenCameraOnUGUIOrGameObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OpenCameraOnUGUIOrGameObject : MonoBehaviour
{
public RawImage rawImage;//相机渲染的UI
public GameObject quad;//相机渲染的GameObject
private WebCamTexture webCamTexture;
void Start()
{
ToOpenCamera();
}
/// <summary>
/// 打开摄像机
/// </summary>
public void ToOpenCamera()
{
StartCoroutine("OpenCamera");
}
public IEnumerator OpenCamera()
{
int maxl = Screen.width;
if (Screen.height > Screen.width)
{
maxl = Screen.height;
}
// 申请摄像头权限
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
//打开渲染图
if (rawImage != null)
{
rawImage.gameObject.SetActive(true);
}
if (quad != null)
{
quad.gameObject.SetActive(true);
}
// 监控第一次授权,是否获得到设备(因为很可能第一次授权了,但是获得不到设备,这里这样避免)
// 多次 都没有获得设备,可能就是真没有摄像头,结束获取 camera
int i = 0;
while (WebCamTexture.devices.Length <= 0 && 1 < 300)
{
yield return new WaitForEndOfFrame();
i++;
}
WebCamDevice[] devices = WebCamTexture.devices;//获取可用设备
if (WebCamTexture.devices.Length <= 0)
{
Debug.LogError("没有摄像头设备,请检查");
}
else
{
string devicename = devices[0].name;
webCamTexture = new WebCamTexture(devicename, maxl, maxl == Screen.height ? Screen.width : Screen.height, 30)
{
wrapMode = TextureWrapMode.Repeat
};
// 渲染到 UI 或者 游戏物体上
if (rawImage != null)
{
rawImage.texture = webCamTexture;
}
if (quad != null)
{
quad.GetComponent<Renderer>().material.mainTexture = webCamTexture;
}
webCamTexture.Play();
}
}
else {
Debug.LogError("未获得读取摄像头权限");
}
}
private void OnApplicationPause(bool pause)
{
// 应用暂停的时候暂停camera,继续的时候继续使用
if (webCamTexture !=null)
{
if (pause)
{
webCamTexture.Pause();
}
else
{
webCamTexture.Play();
}
}
}
private void OnDestroy()
{
if (webCamTexture != null)
{
webCamTexture.Stop();
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)