【发布时间】:2021-01-11 22:06:56
【问题描述】:
我现在已经编写了很多个月的代码,但我对统一和 C# 还是很陌生。目前,我正在尝试创建一个脚本来显示相机供稿,并在按下按钮时拍摄该供稿的静止画面,以便我可以在其上运行 OCR 算法。我从这里获取了我的大部分代码(以及代码 cmets):Can I take a photo in Unity using the device's camera?
我遇到的问题是我不断收到此错误,这使我什至无法运行代码:
Assets/Scripts/WebCam.cs(22,42):错误 CS0103:当前上下文中不存在名称“webCamTexture”
第 22 行在我的代码的 TakePhoto() 函数中。这似乎是范围的问题,但据我所知,由于我对 C# 的掌握非常有限,“webCamTexture”变量在类范围内。因此,它应该可以在任何类 WebCam 的方法中访问。但正如我之前所说,我对 C# 和 Unity 还很陌生,所以也许我只是错过了一些东西。
可能值得注意的是,对于那些只是 C# 并且以前没有使用过 Unity 的人来说,start() 函数应该在应用程序启动时立即运行。因此,理论上,我希望“webCamTexture”变量在执行 TakePhoto() 函数时应该始终具有非空值。
任何帮助将不胜感激。这是有问题的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class WebCamScript : MonoBehaviour
{
public RawImage rawimage;
private WebCamTexture webcamTexture;
private void Start()
{
Debug.Log("Hello World!: WebCamScript Start()");
if (webcamTexture == null)
{
webcamTexture = new WebCamTexture();
}
rawimage.material.mainTexture = webcamTexture;
if (!webcamTexture.isPlaying)
{
webcamTexture.Play();
}
}
public IEnumerator TakePhoto() // Start this Coroutine on some button click
{
// NOTE - you almost certainly have to do this here:
yield return new WaitForEndOfFrame();
// it's a rare case where the Unity doco is pretty clear,
// http://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html
// be sure to scroll down to the SECOND long example on that doco page
Texture2D photo = new Texture2D(webcamTexture.width, webcamTexture.height);
photo.SetPixels(webcamTexture.GetPixels());
photo.Apply();
// //Encode to a PNG
// byte[] bytes = photo.EncodeToPNG();
// //Write out the PNG. Of course you have to substitute your_path for something sensible
// File.WriteAllBytes(your_path + "photo.png", bytes);
}
}
更新:是一个错字。看起来我所需要的只是一双新鲜的眼睛。谢谢大家。话虽如此,我仍然有一些让我摸不着头脑的问题。当我将它链接到我的按钮时,我仍然没有看到我的“takePhoto”功能。任何想法为什么?我更新了上面的代码以反映它的当前状态。见照片: missing script in drop down
【问题讨论】:
-
错字。你的变量是
webcamTexture,但你要求webCamTexture。 -
关于您的 WaitForEndOfFrame 的快速说明,您可以随时更改“脚本执行顺序”,以便此脚本始终在其他脚本之后运行,并且在更新期间仍然进行捕获。