Unity3D 实用技巧 - 快速实现摄像头显示功能

本文介绍如何在Unity3D中使用WebCamera功能,包括创建项目、设置材质、配置相机及控制器,实现调用外部摄像头并显示图像。提供代码示例及高能插件资源。
在应用中,我们可以利用引擎一些内置的API,来驱动硬件的设备功能,例如我们可以通过WebCamera 来调用外部的摄像头。今天小编就与大家一起来简单学习。
下面,咱们直接进入实战模式。 步骤一:创建 Unity3d 的项目,新建 WebCamera 文件夹,并在文件夹下新建材质球CameraPlane.mat,Shader可以选择Unlit/Texture。
步骤二:新建相机Camera,可以命名为WebCamera,并且在WebCamera 创建子对象Plane, 注意Plane的Rotation(x:90 y:180 z:0),接着把CameraPlane.mat 附加上。
步骤三:属于比较重要的一步,新增WebCameraController.cs 组件类,它主要是处理调用外部摄像头,并且显示摄像的内容。代码如下:
    
using System . Collections ; using System . Collections . Generic ; using UnityEngine ; public class WebCameraController : MonoBehaviour { public string DeviceName ; public Vector2 CameraSize ; public float CameraFPS ; //接收返回的图片数据 WebCamTexture _webCamera ; public GameObject Plane ; //作为显示摄像头的面板 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 && Plane != 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 ; _webCamera . Play ( ) ; } public void StopCamera ( ) { Plane . GetComponent < MeshRenderer > ( ) . enabled = false ; _webCamera . Stop ( ) ; } /// <summary> /// 初始化摄像头 /// </summary> public IEnumerator InitCameraCor ( ) { yield return Application . RequestUserAuthorization ( UserAuthorization . WebCam ) ; if ( Application . HasUserAuthorization ( UserAuthorization . WebCam ) ) { WebCamDevice [ ] devices = WebCamTexture . devices ; Debug . Log ( devices . Length ) ; DeviceName = devices [ 0 ] . name ; _webCamera = new WebCamTexture ( DeviceName , ( int ) CameraSize . x , ( int ) CameraSize . y , ( int ) CameraFPS ) ; Plane . GetComponent < Renderer > ( ) . material . mainTexture = _webCamera ; Plane . transform . localScale = new Vector3 ( 1 , 1 , 1 ) ; _webCamera . Play ( ) ; } } }
步骤四:最后直接运行项目看效果哈!
另外其实也有很多大神直接封装一些高能且方便好用的插件,小编就直接分享资源的链接。#同时欢迎下载《虚拟人生》移动端应用。 1、Native Camera for Android & iOS: https://assetstore.unity.com/packages/tools/integration/native-camera-for-android-ios-117802 2、NatDevice - Media Device API: https://assetstore.unity.com/packages/tools/integration/natdevice-media-device-api-162053
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值