using System; using System.Linq; using System.Collections; using System.Collections.Generic; using ZXing; using UnityEngine; using UnityEngine.UI; public class QRCodeReader : MonoBehaviour { public static QRCodeReader Instance { get; private set; } public event Action OnQRCodeRead; [SerializeField] AspectRatioFitter aspectRatioFitter; public RawImage rawImage; public GameObject scanFrame; public WebCamTexture camTexture; private Coroutine c_QRScanningRoutine; void Start() { Instance = this; int backCameraId = 0; bool backCameraEnabled = false; List backCameraIDs = new List(); WebCamDevice[] devices = WebCamTexture.devices; if(devices.Length != 0) { for(int i = 0; i < devices.Length; i++) { if(Application.platform == RuntimePlatform.WindowsEditor) { backCameraEnabled = true; backCameraId = 0; } else { if(devices[i].isFrontFacing) continue; backCameraEnabled = true; backCameraIDs.Add(i); } } if(backCameraIDs.Count != 0) backCameraId = backCameraIDs.First(); } if(!backCameraEnabled) return; camTexture = new WebCamTexture(devices[backCameraId].name); rawImage.texture = camTexture; camTexture.Play(); int orientation = -camTexture.videoRotationAngle; rawImage.rectTransform.localEulerAngles = Vector3.forward * orientation; var ratio = (float)camTexture.width / (float)camTexture.height; aspectRatioFitter.aspectRatio = ratio; float scaleY = camTexture.videoVerticallyMirrored ? -1f : 1f; rawImage.rectTransform.localScale = new Vector3(1f, scaleY, 1f); ScanningQRCode(); } public void ScanningQRCode() { if(c_QRScanningRoutine != null) { StopCoroutine(c_QRScanningRoutine); c_QRScanningRoutine = null; } c_QRScanningRoutine = StartCoroutine(ScanQRCode()); } IEnumerator ScanQRCode() { Result result; while(true) { try { IBarcodeReader barcodeReader = new BarcodeReader(); result = barcodeReader.Decode ( camTexture.GetPixels32(), camTexture.width, camTexture.height ); if(result != null) break; } catch { } yield return new WaitForSeconds(.5f); } yield return new WaitForSeconds(1); OnQRCodeRead?.Invoke(result.Text); } }