c# - WebCamTexture 在第一秒或第二秒出现全 0

标签 c# unity3d colors webcam

我正在使用 WebCamTexture,我在 Start 方法中启动它,然后运行另一个方法。我使用 GetPixels() 获取像素,但是,它们都显示为 (0, 0, 0)。是否有任何解决方法或我可以等待的方法(Unity 似乎使用 while 循环和 WaitForSeconds 崩溃)。这是我当前的启动方法:

void Start () {

    rawImage = gameObject.GetComponent<RawImage> ();
    rawImageRect = rawImage.GetComponent<RectTransform> ();

    webcamTexture = new WebCamTexture();
    rawImage.texture = webcamTexture;
    rawImage.material.mainTexture = webcamTexture;

    webcamTexture.Play();

    Method ();

    loadingTextObject.SetActive (false);
    gameObject.SetActive (true);

}

void Method(){

    print (webcamTexture.GetPixels [0]);

}

这每次都会打印 (0, 0, 0) 颜色。

最佳答案

在协程中执行网络摄像头操作,然后使用 yield return new WaitForSeconds(2); 等待 2 秒,然后调用 webcamTexture.GetPixels

void Start () {

    rawImage = gameObject.GetComponent<RawImage> ();
    rawImageRect = rawImage.GetComponent<RectTransform> ();

    StartCoroutine(startWebCam());

    loadingTextObject.SetActive (false);
    gameObject.SetActive (true);

}

private IEnumerator startWebCam()
{
    webcamTexture = new WebCamTexture();
    rawImage.texture = webcamTexture;
    rawImage.material.mainTexture = webcamTexture;

    webcamTexture.Play();

    //Wait for 2 seconds
    yield return new WaitForSeconds(2);

    //Now call GetPixels
    Method();

}

void Method(){
    print (webcamTexture.GetPixels [0]);
}

或者就像乔在评论部分所说的那样。等待几秒钟是不可靠的。可以等width有东西再读。把

换掉就行了
yield return new WaitForSeconds(2);

while (webcamTexture.width < 100)
{
    yield return null;
}

关于c# - WebCamTexture 在第一秒或第二秒出现全 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379223/

相关文章:

c# - 如何编码和解码非 Ascii 字符?

c# - 圆上的随机点

triggers - 如何在输入另一个对撞机的触发器时禁用对撞机?

javascript - 更改链接悬停时的另一张图像

c# - 在不阻塞 ui UWP 的情况下调用数据库异步方法的最佳实践

C# 添加事件处理程序文字代码块

c# - 如何关闭一个窗体并打开一个新窗体?

c# - C# 项目的目标是 ".NetFramework, Version=v4.5,Profile=Unity Full v3.5",它没有安装在这台机器上

css - 为什么颜色在 CSS 中用十六进制值表示?有历史解释吗?

syntax - 如何在 Visual Studio Code 中更改语法的颜色?