Search code examples
c#unity-game-engineaudio-source

How do I make an audio source play and then when finished the player detector destroys?


Hello I have a 2d Platformer in Unity and I have this sprite with a box collider that detects if its come into contact with the player, when it does it should play the audio source, pause it when the audio source is done it should resume time and destroy the detector. I have tried Enumerators but it doesn't pause time and the detector doesn't stop working.

Here is the code:

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

    
    

}

}


Solution

  • You have to run the routine using StartCoroutine

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

    Actually in order to not have to hardcode it you can directly wait until the full audio clip finished using

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