UnityでQRコードの生成を行いたく、以下のアセットを試しました。
※QRコードの読み取りは試していません。
結論から書くと、非常に簡単です。
QR Code/Barcode Scanner and Generator---Cross Platform について
Asset Storeで公開されている有料アセットです。
QR Code/Barcode Scanner and Generator---Cross Platform
https://www.assetstore.unity3d.com/jp/#!/content/56083
Unity 4.6.4 以降のバージョンが必要
This plugin supports 4.6.x and 5.x
the plugin is an efficient scanning code tools,it runs cross platform , Supports QRCode, Code_128, Code_93, EAN_13, Data Matrix and so on. in addition, which contains a complete project scene, you can use it integrate your project easily.
価格は $20 (2016年9月16日時点)
確認環境
- Unity v5.3.6p2
- Xcode v7.3.1
- MacBook Pro (OS X 10.11.5)
- iPhone 6s (9.3.5)
QRコード生成デモを動かす
- アセットを全てimport
- /Assets/QRcode/Scene/QREncodeScene シーンを開く
- 再生する
- "Enter code text..."欄にエンコードしたい文字列(通常はURLだと思います)を入力し、 encodeをタップ
- その下にQRコードが表示される

- QRコードを読み取れる端末でそのQRコードを読み取ってみる。QRコードは一般的に、あるツールでは読み取れたのに別のツールでは読み取りが失敗するというケースがあるので、想定する読み取りツールがある場合はまず生成したものが使えるかどうかという観点から確認した方が良いと思います。
スクリプトでQRコードの画像を作成する
下記のソース中のコメントとスクショで十分伝わるほど簡単ですが、一応説明を書きます。
-
アセットのプレファブ /Assets/QRcode/Prefab/QRCodeEncodeController をHierarchyに置く
-
QRコードを表示するためのRaw Imageを作る
※エンコードしたQRコード画像がTexture2Dで渡されるので簡単のためそうしていますが、もちろんTexture2Dをどう処理するかは任意です。 -
エンコード処理を呼び出すスクリプトを作成する
QREncodeSample.cs
using UnityEngine;
using UnityEngine.UI;
public class QREncodeSample : MonoBehaviour {
public QRCodeEncodeController qrCodeEncodeController;
public RawImage image;
void Start () {
// エンコード完了時に呼ばれるイベント
qrCodeEncodeController.onQREncodeFinished += encodeFinished;
// 指定した文字列をエンコードする
qrCodeEncodeController.Encode ("https://google.com/");
}
/** エンコード完了時に呼ばれる */
void encodeFinished(Texture2D texture) {
if (texture != null) {
// そのまま表示
image.texture = texture;
}
}
}
4. Inspector上で、1,2で作成したオブジェクトの参照を3のスクリプトのプロパティに設定する
<img width="519" alt="qr_code_sample2.png" src="https://qiita-image-store.s3.amazonaws.com/0/42051/ac4a89b1-4b5a-52ba-9859-af06ce5df708.png">
5. 実行する
<img width="320" alt="qr_code_sample3.png" src="https://qiita-image-store.s3.amazonaws.com/0/42051/19f1f6ee-4fd3-06ed-831a-c7f968995f34.png">
# 補足
## Encode()を呼び出すタイミングの注意点
上記のサンプルコードはStart()内でEncode()を呼び出しています。一方、呼び出される側のQRCodeEncodeControllerの初期化もStart()で行われているため、このままだと先にEncode()を呼び出してエラーになる可能性があります。
回避方法はUnityの一般的な話と同様です。
- 初期化をAwake()やOnEnable()で行うようにQRCodeEncodeControllerのコードを変更する
- Encode()をStart()内ではなく、Update()など初期化完了後に行う
- Unityメニューの Edit -> Project Settings -> Script Execution Order で実行順を指定する
## QRコード生成に必要な最小限の構成
試した結果、以下の3つがあればQRコード生成が可能でした。
- /Assets/QRcode/Prefab/QRCodeEncodeController.prefab
- /Assets/QRcode/Plugins/QRCode.dll
- /Assets/QRcode/Scripts/QRCodeEncodeController.cs
## C#のイベント
QRエンコード完了時のコールバック(C#のイベント)については以下が参考になると思います。
[Unity - Events](https://unity3d.com/jp/learn/tutorials/topics/scripting/events?playlist=17117)
[イベント - C# によるプログラミング入門 | ++C++; // 未確認飛行 C](http://ufcpp.net/study/csharp/sp_event.html)