【问题标题】:Play and wait for audio to finish playing播放并等待音频播放完毕
【发布时间】:2016-03-21 14:13:30
【问题描述】:

在我的项目中,我希望播放声音,然后将对象的活动状态设置为 false,此时两者同时发生,因此不会播放声音。如果我保持活动状态为真,那么我会听到声音播放。

如何确保音频在设置的活动状态切换为 false 之前完成,感谢任何帮助或建议。

这是我的代码选择;

 void OnTriggerEnter(Collider other)
 {
     if (other.tag == "Pick Up") 
     {
         if (!isPlayed) {
             source.Play ();
             isPlayed = true;
         }
     }
     if (other.gameObject.CompareTag ("Pick Up"))
     {
         other.gameObject.SetActive (true);
         count = count + 1;
         SetCountText ();
     }
 }

【问题讨论】:

  • 音频源有一个isPlaying 字段,您可以检查。你试过了吗?
  • 是的,在这种情况下,您必须在 .isPlaying 上的协程中等待 - 就像动画一样。
  • @JoeBlow 他必须在协程中这样做,或者在更新函数上有很多布尔值。协程就是这样做的方法。
  • 就在......

标签: c# unity3d audio triggers unity5


【解决方案1】:

您可以使用它的renderer 隐藏对象,以及关闭任何碰撞器、播放声音,然后将其销毁/设置为非活动状态:

renderer.enabled = false;
gameObject.collider.enabled = false;

audio.PlayOneShot(someAudioClip);
Destroy(gameObject, someAudioClip.length); //wait until the audio has finished playing before destroying the gameobject
// Or set it to inactive

【讨论】:

    【解决方案2】:

    正如乔所说的那样使用协程。每次启用碰撞对象时启动协程。

    void OnTriggerEnter(Collider other)
     {
         if (other.tag == "Pick Up") 
         {
             if (!isPlayed) {
                 source.Play ();
                 isPlayed = true;
             }
         }
         if (other.gameObject.CompareTag ("Pick Up"))
         {
             other.gameObject.SetActive (true);
             count = count + 1;
             SetCountText ();
             StartCoroutine(waitForSound(other)); //Start Coroutine
         }
     }
    
    
    
     IEnumerator waitForSound(Collider other)
        {
            //Wait Until Sound has finished playing
            while (source.isPlaying)
            {
                yield return null;
            }
    
           //Auidio has finished playing, disable GameObject
            other.gameObject.SetActive(false);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多