2017-04-04 184 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方法。我沒有終止該應用程序。我想在應用程序運行時啓用/禁用相機。當我關閉標籤時,指示燈熄滅。 –