简体   繁体   中英

Play and wait for audio to finish playing

in my project I want a sound to play and then for an objects active state to be set to false, at the moment both are happening at the same time so the sound doesn't play. If I keep the active state as true then I will hear the sound play.

How can I make sure that the audio finishes before the set active state is switched to false, any help or advice is appreciated.

Here's a selection of my code;

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

You could hide the object using its renderer , as well as turning off any colliders, play the sound, then destroy/set it to inactive:

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

Use coroutine as Joe Said. Start coroutine each time the collided object is enabled.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM