SoFunction
Updated on 2025-03-06

Unity calls the phone camera to identify the QR code

This article implements Unity calls mobile phone camera, shoot, and then recognizes the QR code to display the content of the QR code.

A file needs to be imported. Now the identification data of this script is placed in Updata. The data volume is particularly large. If you use it, do it and execute it once in a second. I haven't done it here

Download address:

Code:

using ;
using UnityEngine;
using ZXing;
 
public class WebCameraScript : MonoBehaviour
{
 public string LastResult;
 public string Lastresult;
 public Color32[] data;
 private bool isQuit;
 
 public GUITexture myCameraTexture;
 private WebCamTexture webCameraTexture;
 
 private void Start()
 {
 // bool success = (.FOCUS_MODE_CONTINUOUSAUTO);
 // Checks how many and which cameras are available on the device
 for (int cameraIndex = 0; cameraIndex < ; cameraIndex++)
 {
  // We want the back camera
  if (![cameraIndex].isFrontFacing)
  {
  //webCameraTexture = new WebCamTexture(cameraIndex, , );
  webCameraTexture = new WebCamTexture(cameraIndex, 200, 200);
 
  // Here we flip the GuiTexture by applying a localScale transformation
  // works only in Landscape mode
   = new Vector3(1, 1, 1);
  }
 }
 
 // Here we tell that the texture of coming from the camera should be applied 
 // to our GUITexture. As we have flipped it before the camera preview will have the 
 // correct orientation
  = webCameraTexture;
 // Starts the camera
 ();
 //enabled=
 }
 
 public void ShowCamera()
 {
  = true;
 ();
 }
 
 public void HideCamera()
 {
  = false;
 ();
 }
 
 private void OnGUI()
 {
 (new Rect(60, 30*1, , 20), "LastResult:" + LastResult);
 if ((new Rect(0, 0, 100, 100), "ON/OFF"))
 {
  if ()
  HideCamera();
  else
  ShowCamera();
 }
 }
 
 private void Update()
 {
 //data = new Color32[ * ];
 data = webCameraTexture.GetPixels32();
 
 DecodeQR(, );
 }
 
 
 private void DecodeQR(int W, int H)
 {
 if (isQuit)
  return;
 // create a reader with a custom luminance source
 var barcodeReader = new BarcodeReader {AutoRotate = true, TryHarder = true};
 
 // while (true)
 {
  try
  {
  // decode the current frame
  Result result = (data, W, H);
  if (result != null)
  {
   LastResult = ;
   // shouldEncodeNow = true;
   print("i read out::" + );
  }
 
  // Sleep a little bit and set the signal to get the next frame
  (200);
  data = null;
  }
  catch
  {
  }
 }
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.