使用PhotoCapture Unity C#拍照

时间:2019-04-01 08:13:23

标签: c# unity3d

我有一个脚本,应该可以拍摄多张照片。我正在使用PhotoCapture,但出现错误,使其无法捕获第二张照片。我在photoCaptureObject.StartPhotoModeAsync(cameraParameters, result =>行上收到“值不能为空”错误,但我不明白为什么会这样。

我已注释掉photoCaptureObject = null;行,以便photoCaptureObject不应为null。 if (photoCaptureObject == null) return;行还证明photoCaptureObject不为空。

PhotoCapture photoCaptureObject = null;
Texture2D targetTexture = null;
public string path = "";
CameraParameters cameraParameters = new CameraParameters();

private void Awake()
{
    var cameraResolution = PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First();
    targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height);

    // Create a PhotoCapture object
    PhotoCapture.CreateAsync(false, captureObject =>
    {
        photoCaptureObject = captureObject;
        cameraParameters.hologramOpacity = 0.0f;
        cameraParameters.cameraResolutionWidth = cameraResolution.width;
        cameraParameters.cameraResolutionHeight = cameraResolution.height;
        cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
    });
}

private void Update()
{
    // if not initialized yet don't take input
    if (photoCaptureObject == null) return;

    if (Input.GetKeyDown(KeyCode.K) || Input.GetKeyDown("k"))
    {
        Debug.Log("k was pressed");

        VuforiaBehaviour.Instance.gameObject.SetActive(false);

        // Activate the camera
        photoCaptureObject.StartPhotoModeAsync(cameraParameters, result =>
        {
            if (result.success)
            {
                // Take a picture
                photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory);
            }
            else
            {
                Debug.LogError("Couldn't start photo mode!", this);
            }
        });
    }
}

这之间有一些代码可以更改拍摄的照片,依此类推,但我认为该代码不是问题的一部分。

private void OnStoppedPhotoMode(PhotoCapture.PhotoCaptureResult result)
{
    // Shutdown the photo capture resource
    VuforiaBehaviour.Instance.gameObject.SetActive(true);
    photoCaptureObject.Dispose();
    //photoCaptureObject = null;
    Debug.Log("Photomode stopped");
}

那么还有什么可以为空?是StartPhotoModeAsync吗?如何解决此问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

好的,现在我很感谢Henriks的评论。

Unity专门针对StartPhotoModeAsync这样说:

  

在任何给定的情况下,只有一个PhotoCapture实例可以启动照片模式   时间

在我说应该始终使用PhotoCapture.StopPhotoModeAsync之前,我将重点放在句子上,因为启用PhotoCaptureMode会消耗更多功率,所以我从未想到实例在停止后不会再次启动。

现在,我在按键更新中仅拥有TakePhotoAsync,并且由于我制作的应用程序应始终能够捕获照片,因此无法停止PhotoMode。