ソースコード
UniTaskを使用しています。
ScreenShot.cs
using Cysharp.Threading.Tasks;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Windows.WebCam;
public class ScreenShot : MonoBehaviour
{
[SerializeField] private RawImage rawImage = default;
private async void Start()
{
var token = this.GetCancellationTokenOnDestroy();
rawImage.texture = await WebCamScreenShot(cancellationToken: token);
}
private async UniTask<Texture2D> WebCamScreenShot(Texture2D result = null, CancellationToken cancellationToken = default)
{
bool uploaded = false;
if (result == null)
{
var cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
result = new Texture2D(cameraResolution.width, cameraResolution.height);
}
PhotoCapture photoCaptureObject = null;
PhotoCapture.CreateAsync(true, photoCapture =>
{
photoCaptureObject = photoCapture;
CameraParameters cameraParameters = new CameraParameters();
cameraParameters.hologramOpacity = 0.9f;
cameraParameters.cameraResolutionWidth = result.width;
cameraParameters.cameraResolutionHeight = result.height;
cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
photoCaptureObject.StartPhotoModeAsync(cameraParameters, _ => photoCaptureObject.TakePhotoAsync((_, photoCaptureFrame) =>
{
photoCaptureFrame.UploadImageDataToTexture(result);
uploaded = true;
}));
});
await UniTask.WaitUntil(() => uploaded, cancellationToken: cancellationToken);
photoCaptureObject.StopPhotoModeAsync(_ => { photoCaptureObject?.Dispose(); });
return result;
}
}
注意点
WebCamとMicrophoneの権限が必要です。
Project Settings > Player > Publishing Settinggs > Capabilities > WebCamとMicrophoneにチェック。
HoloLens2上でポップアップが出るので許可をしてください。
アプリ毎の権限はHoloLens2の設定 > アプリで確認できます。
自分の場合は別のプロジェクト名でビルドし直すと動きました。
アプリを再インストールしても治りませんでした。