using System; using System.Collections; using System.Linq; using UnityEngine; using UnityEngine.UI; using ZXing; public class QRCode : MonoBehaviour { public RawImage rawImage; private WebCamTexture webCamTexture; private Color32[] data; private BarcodeReader barcodeReader; public Text text; private int width; private int height; private int lastRotationAngle; private RectTransform rectTransform; private IEnumerator Start() { width = Screen.width; height = Screen.height; rectTransform = GetComponent(); barcodeReader = new BarcodeReader(); yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); if (Application.HasUserAuthorization(UserAuthorization.WebCam)) { var device = WebCamTexture.devices.FirstOrDefault(o => !o.isFrontFacing); webCamTexture = new WebCamTexture(device.name, width, height, 25); data = new Color32[webCamTexture.width * webCamTexture.height]; rawImage.texture = webCamTexture; webCamTexture.Play(); //InvokeRepeating(nameof(CheckQRCode), 0, 1f); } } private IEnumerator CheckQRCode() { yield return null; if (webCamTexture != null && webCamTexture.isPlaying) { data = webCamTexture.GetPixels32(); if (data != null) { try { var tResult = barcodeReader.Decode(data, webCamTexture.width, webCamTexture.height); if (tResult != null) { text.text = tResult.Text; //$"{tResult.BarcodeFormat}:{tResult.Text}"; } } catch (Exception ex) { Debug.LogError(ex.Message); } } } } private void OnEnable() { if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCamTexture != null) { webCamTexture.Play(); } } private void OnDisable() { if (Application.HasUserAuthorization(UserAuthorization.WebCam) && webCamTexture != null) { webCamTexture.Stop(); } } private void Update() { if (webCamTexture != null && lastRotationAngle != webCamTexture.videoRotationAngle) { OnOrientationChanged(); lastRotationAngle = webCamTexture.videoRotationAngle; } StartCoroutine(CheckQRCode()); } private void OnOrientationChanged() { transform.localRotation = Quaternion.Euler(0, 0, -webCamTexture.videoRotationAngle); //if (webCamTexture.videoRotationAngle % 180 != 0) //{ // rectTransform.sizeDelta = new Vector2(height, width); //} //else //{ // rectTransform.sizeDelta = new Vector2(width, height); //} } private void OnGUI() { GUILayout.Label(webCamTexture.videoRotationAngle.ToString()); GUILayout.Label(webCamTexture.videoVerticallyMirrored.ToString()); } }