Unity+Hololens二维码识别
文章下方附带zxing.unity.dll文件和Unity项目源码
进行二维码识别之前,需要对Hololens的开发环境进行配置,以及Unity开发Hololens需要的一些设置,介绍文章很多,不多说了。
开发环境
Unity 2018.4.14 (IL2CPP模式下)
Hololens 1代
VS 2019
识别二维码是基于zxing.unity.dll,需要放在Plugins文件夹下,并设置为所有平台通用
上代码
using UnityEngine;
using System.Collections;
using ZXing;
using UnityEngine.UI;
using System.Threading;
using System;
public class QRcode : MonoBehaviour
{
/// <summary> 包含RGBA </summary>
private Color32[] data;
/// <summary> 相机捕捉到的图像 </summary>
private WebCamTexture webCameraTexture;
/// <summary> ZXing中的方法,可读取二维码中的内容 </summary>
private BarcodeReader barcodeReader;
/// <summary> 计时,0.5s扫描一次 </summary>
private int timer = 500;
public Text QRcodeText;
public Animation scanAni;
public AudioSource audio;
public RawImage cameraTexture;
Thread thread;
public System.Collections.Concurrent.ConcurrentQueue<System.Action> _MainThreadQueue =
new System.Collections.Concurrent.ConcurrentQueue<Action>();
/// <summary>
/// 初始化
/// </summary>
/// <returns></returns>
IEnumerator Start()
{
barcodeReader = new BarcodeReader();
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//请求授权使用摄像头
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;//获取摄像头设备
string devicename = devices[0].name;
webCameraTexture = new WebCamTexture(devicename, 400, 300);//获取摄像头捕捉到的画面
cameraTexture.enabled = true;
cameraTexture.texture = webCameraTexture;
webCameraTexture.Play();
scanAni.Play();
thread = new Thread(ScanQRcode);
thread.Start();
}
}
void Update()
{
while (_MainThreadQueue.Count > 0)
{
if (_MainThreadQueue.TryDequeue(out Action func))
{
func?.Invoke();
}
}
}
private void OnDisable()
{
thread.Abort();
}
/// <summary>
/// 子线程
/// </summary>
private void ScanQRcode()
{
while (true)
{
_MainThreadQueue.Enqueue(() =>
{
data = webCameraTexture.GetPixels32();//相机捕捉到的纹理
DecodeQR(webCameraTexture.width, webCameraTexture.height);
});
Thread.Sleep(timer);
}
}
/// <summary>
/// 识别二维码并显示其中包含的文字、URL等信息
/// </summary>
/// <param name="width">相机捕捉到的纹理的宽度</param>
/// <param name="height">相机捕捉到的纹理的高度</param>
private void DecodeQR(int width, int height)
{
var br = barcodeReader.Decode(data, width, height);
if (br != null)
{
QRcodeText.text = br.Text;
audio.Play();
}
else
{
QRcodeText.text = "";
}
}
}
效果展示
(这是电脑上测试,Hololens 1代亲测OK)
zxing.unity.dll 提取码:881g
Unity项目源码 提取码:vqxu