需求:
打开相机并显示在UI上
效果:
注意:
电脑可能有多个摄像头,注意名称
代码:
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endifnamespace 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();}}
#endifpublic 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;}}
}
一键三联
点赞·留言·收藏
如果可以帮到你,好用的话,记得一键三连。
毕竟博主写文章是靠爱发电,所以爱会消失对不对。