Unity打开摄像头并显示在UI
- 电脑硬件
- 2025-08-31 20:00:02

需求:
打开相机并显示在UI上
效果: 注意:电脑可能有多个摄像头,注意名称
代码: using System; using System.Linq; using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif namespace Streamlab.XingJiKongLong { #if UNITY_EDITOR [CustomEditor(typeof(RealCameraDeviceManager))] public class RealCameraDeviceManagerEditor : Editor { private RealCameraDeviceManager script; private void OnEnable() { script = (RealCameraDeviceManager)target; } public override void OnInspectorGUI() { base.OnInspectorGUI(); GUILayout.BeginHorizontal(); { if (GUILayout.Button("初始化", GUILayout.Height(50))) { script.InitDevices(); } if (GUILayout.Button("打开", GUILayout.Height(50))) { script.Play(); } if (GUILayout.Button("关闭", GUILayout.Height(50))) { script.Stop(); } if (GUILayout.Button("暂停", GUILayout.Height(50))) { script.Pause(); } } GUILayout.EndHorizontal(); } } #endif public class RealCameraDeviceManager : MonoBehaviour { public bool Inited = false; public bool IsPlaying = false; private WebCamDevice CurrentWebCamDevice; private WebCamTexture CurrentWebCamTexture; public RawImage image; /// <summary> /// 默认摄像头设备名称 /// </summary> public string DefaultWebCamDeviceName = "USB2.0 PC CAMERA"; public List<string> WebCamDevice = new List<string>(); public void InitDevices() { WebCamDevice[] devices = WebCamTexture.devices; if (devices.Length == 0) { throw new Exception("暂未识别到摄像头设备,请检查摄像头有没有"); } else { WebCamDevice.Clear(); foreach (var item in devices) { Debug.Log($"摄像头设备【{item.name}】"); WebCamDevice.Add(item.name); } } if (string.IsNullOrEmpty(DefaultWebCamDeviceName)) { DefaultWebCamDeviceName = devices[0].name; } CurrentWebCamDevice = devices.Where(x => x.name == DefaultWebCamDeviceName).FirstOrDefault(); CurrentWebCamTexture = new WebCamTexture(CurrentWebCamDevice.name); if (image == null) { throw new Exception("未指定显示摄像头的UI"); } image.texture = CurrentWebCamTexture; Inited = true; } public void Play() { if (Inited == false) { throw new Exception("未初始化摄像头设备"); } CurrentWebCamTexture.Play(); IsPlaying = true; } public void Stop() { if (Inited == false) { throw new Exception("未初始化摄像头设备"); } CurrentWebCamTexture.Stop(); IsPlaying = false; } public void Pause() { if (Inited == false) { throw new Exception("未初始化摄像头设备"); } CurrentWebCamTexture.Pause(); IsPlaying = false; } } } 一键三联点赞·留言·收藏
如果可以帮到你,好用的话,记得一键三连。
毕竟博主写文章是靠爱发电,所以爱会消失对不对。
Unity打开摄像头并显示在UI由讯客互联电脑硬件栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Unity打开摄像头并显示在UI”
下一篇
SAP归档生产订单的序列号查询