HoloLens2 QRコード読み取りのやり方

開発環境

  • HoloLens2
  • Windows 10 pc
  • Unity 2019.4.1f1
  • MRTK ver2.5.3

やり方

QRCodeReader.cs
using UnityEngine;
using Microsoft.MixedReality.QR;
using UnityEngine.UI;

public class QRCodeReader : MonoBehaviour
{
    [SerializeField] Text text = null;
    QRCodeWatcher qrCodeWatcher;
    // Start is called before the first frame update
    async void Start()
    {
        Debug.Log(QRCodeWatcher.IsSupported());
        text.text = QRCodeWatcher.IsSupported().ToString();
        if (QRCodeWatcher.IsSupported()) //サポートされているか確かめる。
        {
            await QRCodeWatcher.RequestAccessAsync();  //アクセス許可を取る。
            qrCodeWatcher = new QRCodeWatcher();
            qrCodeWatcher.Added += AddedQRCode; //QRCodeを発見した時の処理を追加。
            qrCodeWatcher.Start(); //スキャンを開始。
        }
    }
    // QRCodeを発見した時の処理。
    private void AddedQRCode(object sender, QRCodeAddedEventArgs e) 
    {
        text.text = e.Code.Data;
    }

    // スキャンを止める。
    public void Stop()
    {
        qrCodeWatcher.Stop(); //スキャンを停止
        qrCodeWatcher.Added -= AddedQRCode; //QRCodeを発見した時の処理を削除
    }
}

※ QRCodeWatcher.Addedに追加できるデリゲートの型は void(object,QRCodeAddedEventArgs)のみ。

上のスクリプトをプロジェクトに追加し、適当なオブジェクトに追加。

textプロパティを設定してビルド、実機で実行。

この記事を書いた人

azure-recipe-user