播放并等待音频播放完毕 [英] Play and wait for audio to finish playing

查看:456
本文介绍了播放并等待音频播放完毕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在设置的活动状态切换为false之前,如何确保音频结束,请多多帮助或建议.

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

这是我选择的代码;

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

推荐答案

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

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

这篇关于播放并等待音频播放完毕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆