Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebCamTexture Coming Up With All 0s in the First Second or Two

I am using a WebCamTexture and I start it in my Start method, then I run another method. I get the pixels using GetPixels(), however, they all come up as (0, 0, 0). Is there any fix to this or way I can wait (Unity seems to crash using while loops and WaitForSeconds). Here is my current Start method:

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

}

And this prints a (0, 0, 0) color every time.

like image 679
Dylan Siegler Avatar asked Jan 28 '26 20:01

Dylan Siegler


1 Answers

Do your webcam stuff in a coroutine then wait for 2 seconds with yield return new WaitForSeconds(2); before calling 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]);
}

Or like Joe said in the comment section. Waiting for seconds is not reliable. You can just wait for the width to have something before reading it.Just replace the

yield return new WaitForSeconds(2);

with

while (webcamTexture.width < 100)
{
    yield return null;
}
like image 107
Programmer Avatar answered Jan 30 '26 08:01

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!