播放并等待音频播放完毕

Play and wait for audio to finish playing

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

您可以使用 renderer 隐藏对象,并关闭任何碰撞器,播放声音,然后 destroy/set 将其设为非活动状态:

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

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

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