- Home /
Question by
JokerZappie · Mar 10, 2017 at 07:06 AM ·
c#unity 5texture2dwebcamtexturedevices
How to make a WebCamTexture 'run'?
I'm trying to use a WebCamTexture object to take a picture when a button is pressed, but I'm stuck with the following error:
Cannot get pixels when webcam is not running
UnityEngine.WebCamTexture:GetPixels()
Here's my code (note that it's only the code regarding the problem):
private WebCamTexture _cam;
private Texture2D _picture;
void Start() {
_cam = new WebCamTexture();
if (WebCamTexture.devices.Length > 1) {
_cam = new WebCamTexture(WebCamTexture.devices[1].name);
Debug.Log("Set WebCamTexture to device 2/" + WebCamTexture.devices.Length);
}
else if (WebCamTexture.devices.Length > 0) { // This returns true in my case
_cam = new WebCamTexture(WebCamTexture.devices[0].name);
Debug.Log("Set WebCamTexture to 1/" + WebCamTexture.devices.Length);
}
_cam.Play();
}
private bool UpdatePicture() {
if (!_cam.isPlaying) {
_cam.Play();
}
if (_picture == null)
_picture = new Texture2D(_cam.width, _cam.height, TextureFormat.RGB24, false);
if (_cam.didUpdateThisFrame) {
_picture.SetPixels(_cam.GetPixels());
_picture.Apply();
return true;
}
return false;
}
The problem is at the if(_cam.didUpdateThisFrame()), this is always false and when I remove the if statement the above error occurs. Does anybody know why this may happen or how to solve this? Thanks.
Comment