- Home /
WebcamTexture not correctly disabled on scene changes
When making scene transitions my WebcamTexture doesn't get properly destroyed. During the next scene, creating a new WebcamTexture incorrectly initializes the device parameters and never updates frames. Also after Stopping playmode, my camera stays on (with the light on), and the only way to free it is to close the unity editor.
This is a minimum example, where I can reproduce this issue. Just use this component on a scene object and press enter to switch scenes.
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CamTest : MonoBehaviour {
WebCamTexture liveFeed;
IEnumerator Start ()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
liveFeed = new WebCamTexture();
liveFeed.Play();
}
else
Debug.LogWarning("Camera access not obtained!");
}
void OnDisable ()
{
if (liveFeed && liveFeed.isPlaying)
liveFeed.Stop();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Return))
{
SceneManager.LoadScene(gameObject.scene.name);
}
}
}
Answer by AndyUr · May 28, 2018 at 11:07 PM
Seems like I found a working solution. Using a static WebcamTexture variable keeps the camera correctly initialized during scene transitions Here's the fixed code (plus some setup to show the feed on a RawImage).
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class CamTest : MonoBehaviour {
static WebCamTexture liveFeed;
public RawImage feed;
IEnumerator Start ()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
if(!liveFeed)
liveFeed = new WebCamTexture();
liveFeed.Play();
feed.texture = new Texture2D(liveFeed.width, liveFeed.height, TextureFormat.RGBA32, false);
}
else
Debug.LogWarning("Camera access not obtained!");
}
void OnDisable ()
{
if (liveFeed && liveFeed.isPlaying)
liveFeed.Stop();
}
void Update()
{
if(liveFeed && liveFeed.didUpdateThisFrame)
{
Color32[] buffer = liveFeed.GetPixels32();
(feed.texture as Texture2D).SetPixels32(buffer);
(feed.texture as Texture2D).Apply();
Debug.Log("ding");
}
if(Input.GetKeyDown(KeyCode.Return))
{
SceneManager.LoadScene(gameObject.scene.name);
}
}
}
Your answer
Follow this Question
Related Questions
Script for changing levels 3 Answers
how to use WebcamTexture working well on mobile device 0 Answers
2013 Face tracking plugin 1 Answer
Projector with WebCamTexture as texture 0 Answers
Light Data from WebCam? 0 Answers