Reading and Generating QR codes with C# in Unity 3D — the easy way
When You Have Had to Spend Hours to Implement a Simple QR Scanner for your Dream Game
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.
If you love game development, check out my article on Creating Godot Game Engine Editor Tools And Plugins For More Efficient Game Design Workflows.
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 you a sample code that 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 reason to pay for any of those mostly broken QR plugins, now is there?
rendering QR codes from a text in Unity
This worked from within most libraries but you can use this one for 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 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.
Disclaimer
I was using Unity 5.3.5 to experiment with this.
Dear Reader,
Please clap, follow and join my newsletter if you like this content and you would like to support 🙇🏻♂️. You can connect with me on X (Twitter), Linkedin, Instagram & Github, and find out more on nenuadrian.com!
If you liked this article, you may also enjoy:
- Dante’s Code Hell Inferno: the Nine Layers
- The Code Purgatorio: Ascension to Clean Code
- How To Not Be a Run-of-the-Mill Software Engineer
- Plato’s Republic Of Software Engineering: A Philosophical Perspective
- Code 💻: The Modern Driving Skill — Why It’s as Crucial Today as Driving 🚙Was in the Past
- Diversify your Experience as you would your Investment Portfolio!