如何播放音频源,然后播放器检测器完成后销毁?

问题描述

你好,我在 Unity 中有一个 2d 平台游戏,我有一个带有盒子碰撞器的精灵,它检测它是否与玩家接触,当它发生时它应该播放音频源,当音频源完成时暂停它应该恢复时间并销毁探测器。我尝试过枚举器,但它不会暂停时间,检测器也不会停止工作。

代码如下:

public AudioSource UFOTALK1;

public GameObject player;

public BoxCollider2D sp;

bool used = false;

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        if (!used)
        {
            waiter();
            UFOTALK1.Play();
            used = true;
        }
        else
        {

        }
        
        
    }
}



void PauseGame()
{
    player.GetComponent<PlayerMovement>().enabled = false;
}

void ResumeGame()
{
    player.GetComponent<PlayerMovement>().enabled = true;
}

IEnumerator waiter()
{
    PauseGame();
    

    
    yield return new WaitForSeconds(7.392f);
    sp.enabled = false;
    ResumeGame();

    
    

}

}

解决方法

您必须使用 StartCoroutine

运行例程
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        if (!used)
        {
            StartCoroutine (waiter());

            UFOTALK1.Play();
            used = true;
        }   
    }
}

其实为了不用硬编码,你可以直接等到完整的音频剪辑完成使用

yield return new WaitForSeconds (UFOTALK.clip.length);