我正在使用WebCamTexture,并在Start方法中启动它,然后运行另一个方法。我使用GetPixels()获取像素,但是它们都以(0, 0, 0)的形式出现。有什么解决办法或我可以等待的方式吗(Unity似乎使用while循环和WaitForSeconds崩溃了)。这是我当前的Start方法:

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]);
}


还是像乔在评论部分所说的那样。等待几秒钟是不可靠的。您可以等一下宽度后再阅读。只需更换

yield return new WaitForSeconds(2);




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

08-19 03:23