Reading and Generating QR codes with C# in Unity 3D — the easy way

I have had a tremendously difficult time on my quest to add a QR code generator/renderer and a QR reader into the GUI of a Unity 5.3.5 project, and this is the easy way out.

I am slightly over-exaggerating here. We talking about only around two days here, BUT that is still too much time for such a simple feature in this day and age and I feel other people might get delayed in pursuing their actual goals for their game to tackle this side-development-task.

There are a number of paid QR plugins out there that you can purchase, but for all I have found the reviews do not recommend their usage or otherwise do not promote them as worth paying for.

I found myself forced to build libraries found around the world wide web (since Unity still works only with ~.NET 2 as of this article) and going through a painful process of trial and error, experimenting with multiple libraries specifically created or not for Unity. This may also have been caused by the fact that I had not used QR libraries before so I was not necessarily familiar with which ones work and which are legacy.

The smooth solution

The ZXing library did wonders for me, once I got it to work. Moreover, it allows you to extend it to work and play with other types of bar codes.

You can download my version of the DLL which you need to add as a reference in your Unity project.

It is specifically tailored (but not by me) to run with Unity: zxing.unity.dll for Unity.

Code

I will spare you any more boring details and give a sample code which you can tweak and make work in your own Unity projects within minutes.

using ZXing;
using ZXing.QrCode;

private WebCamTexture camTexture;
private Rect screenRect;
void Start() {
screenRect = new Rect(0, 0, Screen.width, Screen.height);
camTexture = new WebCamTexture();
camTexture.requestedHeight = Screen.height;
camTexture.requestedWidth = Screen.width;
if (camTexture != null) {
camTexture.Play();
}
}

void OnGUI () {
// drawing the camera on screen
GUI.DrawTexture (screenRect, camTexture, ScaleMode.ScaleToFit);
// do the reading — you might want to attempt to read less often than you draw on the screen for performance sake
try {
IBarcodeReader barcodeReader = new BarcodeReader ();
// decode the current frame
var result = barcodeReader.Decode(camTexture.GetPixels32(),
camTexture.width, camTexture.height);
if (result != null) {
Debug.Log(“DECODED TEXT FROM QR: “ + result.Text);
}
} catch(Exception ex) { Debug.LogWarning (ex.Message); }
}

It proved to be so straightforward in the end that I banged my head on the table out of sheer frustration due to spending so much time trying out Unity tutorials and libraries.

No reasons to pay for any of those mostly broken QR plugins, now is there?

rendering QR codes from text in Unity

This worked from within most libraries but you can use this one of both purposes (reading and writing QR).

private static Color32[] Encode(string textForEncoding, 
int width, int height) {
var writer = new BarcodeWriter {
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions {
Height = height,
Width = width
}
};
return writer.Write(textForEncoding);
}

UPDATED: Use the following method to generate a 2D texture and display in in the GUI.

public Texture2D generateQR(string text) {
var encoded = new Texture2D (256, 256);
var color32 = Encode(text, encoded.width, encoded.height);
encoded.SetPixels32(color32);
encoded.Apply();
return encoded;
}

Here is a short example of how you could display this using the GUI API.

Texture2D myQR = generateQR("test");
if (GUI.Button (new Rect (300, 300, 256, 256), myQR, GUIStyle.none)) {}

This should allow you to display the QR code as a button.

Was it so hard?

No. And this is exactly the point. There are countless un-fully-answered questions on the topic scattered around the web (on the Unity spectrum).

It should be easy and more easily available to (new Unity) developers. QR codes can have many uses in augmented reality apps and these simple examples should, I believe, be part of the actual Unity documentation.

--

--

--

Adrian is a software engineer, passionate about elegant code, photography and writing. Connect @ nenuadrian.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Recipe #8: Check Supply and Borrow Rate on Compound

Abolish 1 DENA Registration Fee Policy

API and REST API

Automating the creation of a new project.

DELETE vs. DROP vs. TRUNCATE

Simple Object Movement in Unity

Under the Hood:`ls -l *.c`

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adrian M. Nenu 😺

Adrian M. Nenu 😺

Adrian is a software engineer, passionate about elegant code, photography and writing. Connect @ nenuadrian.com

More from Medium

Sending SMSes with Python, ADB, and Android 9 without any API

Screenshot of “Download F-DROID” button

Day 2 of my journey to becoming a Unity game developer

Mobile Applications In Unity: Rainy Day Insurance — Unity Teams and AWS Services Set Up

How Not To Make A Game