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.
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;
}