播放并等待音频播放完毕

时间:2016-03-21 14:13:31

标签: c# unity3d audio triggers unity5

在我的项目中,我希望播放声音然后将对象活动状态设置为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 ();
     }
 }

2 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:2)

使用coroutine作为Joe Said。每次启用碰撞对象时启动协同程序。

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);
    }