2017-04-04 189 views
0

我正在使用以下脚本来启用/禁用WebGL上的摄像头。Unity WebGL WebcamTexture摄像头灯在禁用摄像头后保持亮起

它在编辑器上工作正常,但在浏览器上,停用WebcamTexture后,摄像头灯仍然亮着。

它发生在Chrome和Firefox上。

任何想法?

谢谢。

WebCamTexture _webcamTexture; 

public void Enable() 
{ 
    #if UNITY_EDITOR || DEVELOPMENT_BUILD 
    Debug.Log("Enable"); 
    #endif 

    _enabled = true; 
} 

public void Disable() 
{ 
    #if UNITY_EDITOR || DEVELOPMENT_BUILD 
    Debug.Log("Disable"); 
    #endif 

    _enabled = false; 
} 

#region MONOBEHAVIOUR 

void Update() 
{ 
    if(_enabled) 
    { 
     if(_webcamTexture == null) 
     { 
      while(!Application.RequestUserAuthorization(UserAuthorization.WebCam).isDone) 
      { 
       return; 
      } 

      if (Application.HasUserAuthorization(UserAuthorization.WebCam)) 
      { 
       #if UNITY_EDITOR || DEVELOPMENT_BUILD 
       Debug.Log("Webcam authorized"); 
       #endif 

       _webcamTexture = new WebCamTexture (WebCamTexture.devices[0].name); 
       _webcamTexture.Play(); 
      } 
      else 
      { 
       #if UNITY_EDITOR || DEVELOPMENT_BUILD 
       Debug.Log("Webcam NOT authorized"); 
       #endif 
      } 
     } 
     else if (_webcamTexture.isPlaying) 
     { 
      if(!_ready) 
      { 
       if (_webcamTexture.width < 100) 
       { 
        return; 
       } 

       _ready = true; 
      } 

      if(_webcamTexture.didUpdateThisFrame) 
      { 
       _aspectRatioFitter.aspectRatio = (float)_webcamTexture.width/(float)_webcamTexture.height; 

       _imageRectTransform.localEulerAngles = new Vector3 (0, 0, -_webcamTexture.videoRotationAngle); 

       _image.texture = _webcamTexture; 
      } 
     } 
    } 
    else 
    { 
     if(_webcamTexture != null) 
     { 
      _webcamTexture.Stop(); 
      _webcamTexture = null; 

      _image.texture = null; 
     } 
    } 
} 

#endregion 

回答

0

代码在编辑器中工作的唯一原因是编辑器会为您清理一些内容。一旦您点击停止,即使没有WebCamTexture.Stop();被调用,相机也会自动停止。

不幸的是,这在构建中不会发生。你必须明确地呼叫WebCamTexture.Stop();停止它。正确的位置在Disable()函数中。

public void Disable() 
{ 
    if(_webcamTexture != null) 
    { 
     _webcamTexture.Stop(); 
    } 
} 

编辑:

而不是使用一个布尔变量来禁用摄像头,使功能和功能连接到您的停止按钮。当该功能被调用时,它会停止相机。

public void disableCamera() 
{ 
    if(_webcamTexture != null) 
    { 
     _webcamTexture.Stop(); 
    } 
} 
+0

感谢您的回答。我打电话给_webcamTexture.Stop();更新时将_enabled设置为false。我已经在Disable方法中试过了。它不应该有任何区别,对吧? –

+0

我知道你是。这是完全错误的。当应用程序存在时,'Update'函数被终止。如果if语句甚至没有运行,该怎么办?这就是为什么你应该停止/结束'OnDisable'函数而不是'Update'函数中的东西。试试我的解决方案。当你关闭标签时会发生这个问题? – Programmer

+0

当我按下UI按钮时,将调用Disable方法。我没有终止该应用程序。我想在应用程序运行时启用/禁用相机。当我关闭标签时,指示灯熄灭。 –