Skip to content

Instantly share code, notes, and snippets.

@baobao
Last active March 2, 2025 07:49
Show Gist options
  • Save baobao/ad928907ebcfb7db0ef20f71bad4c6b0 to your computer and use it in GitHub Desktop.
Save baobao/ad928907ebcfb7db0ef20f71bad4c6b0 to your computer and use it in GitHub Desktop.
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class SampleQRReader : MonoBehaviour
{
private string _result = "";
private WebCamTexture _webCam;
void Awake()
{
ReadyWebCamAsync().Forget();
}
void Update()
{
if (_webCam != null && QRCodeHelper.TryRead(_webCam, out var result))
{
_result = result;
}
else
{
_result = "ERROR";
}
CheckDebugMode();
}
private async UniTask ReadyWebCamAsync()
{
await Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam) == false)
{
return;
}
WebCamDevice[] devices = WebCamTexture.devices;
if (devices == null || devices.Length == 0)
{
return;
}
_webCam = new WebCamTexture(devices[0].name, Screen.width, Screen.height, 12);
_webCam.Play();
}
void OnGUI()
{
_isDebug = GUILayout.Toggle(_isDebug, "DEBUGモード", GUILayout.Height(100f), GUILayout.Width(100f));
GUILayout.Label(_result, GUILayout.Width(300f), GUILayout.Height(200f));
}
#region Debug
private bool _isDebug = true;
private bool _isDebugMode;
private GameObject _debugView;
void CheckDebugMode()
{
if (_isDebugMode != _isDebug)
{
_isDebugMode = _isDebug;
if (_isDebugMode)
ShowDebugView();
else
HideDebugView();
}
}
/// <summary>
/// 画面右上にWebCamを表示させる
/// </summary>
void ShowDebugView()
{
if (_debugView != null) return;
_debugView = new GameObject("DebugQR");
var debugRawObj = new GameObject("Raw");
debugRawObj.transform.SetParent(_debugView.transform, false);
var rawImage = debugRawObj.AddComponent<RawImage>();
var c = _debugView.AddComponent<Canvas>();
c.renderMode = RenderMode.ScreenSpaceOverlay;
rawImage.texture = _webCam;
float w = 200f;
float h = w * Screen.width / Screen.height;
rawImage.rectTransform.sizeDelta = new Vector2(w, h);
rawImage.rectTransform.anchorMax = new Vector2(1f, 1f);
rawImage.rectTransform.anchorMin = new Vector2(1f, 1f);
rawImage.rectTransform.anchoredPosition = new Vector2(-w * 0.5f, -h * 0.5f);
}
void HideDebugView()
{
Destroy(_debugView);
_debugView = null;
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment