Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Playing audio only once

Discussion in 'Scripting' started by MooseGames, Jul 15, 2023.

  1. MooseGames

    MooseGames

    Joined:
    Jul 5, 2023
    Posts:
    2
    If two objects in my game collide, the gameOverSound will play. However, there is one problem. Those objects keep touching each other, causing the gameOverSound to play repeatedly, resulting in a continuous cracking sound. How can I make it play only once?
    Thanks!

    private void GameOver2()
    {
    isGameEnded = true;
    loseText.text = "FROG DIED";
    loseText.gameObject.SetActive(true);
    restartButtonText.text = "Try Again\n(Click Or Press R)";
    restartButtonPanel.SetActive(true);

    canMovePlayers = false;

    playerMovement.GameOver(); // Kutsu GameOver-metodia CharacterMovement-komponentissa
    SetTLRVisibility(true); // Tee TLR-objekti näkyväksi pelin päättyessä

    // Lopeta taustamusiikin toistaminen
    if (themeSong != null)
    {
    audioSource.Stop();
    }

    // Toista GameOver-ääniefekti, jos se ei ole jo toistossa
    if (gameOverSound != null && !audioSource.isPlaying)
    {
    audioSource.PlayOneShot(gameOverSound);
    }
    }
     
  2. Tudamun

    Tudamun

    Joined:
    Sep 20, 2022
    Posts:
    11
    Code (CSharp):
    1. private void GameOver2()
    2. {
    3. // Toista GameOver-ääniefekti, jos se ei ole jo toistossa
    4. if (!isGameEnded && gameOverSound != null && !audioSource.isPlaying)
    5. {
    6.     audioSource.PlayOneShot(gameOverSound);
    7. }
    8. isGameEnded = true;
    9. loseText.text = "FROG DIED";
    10. loseText.gameObject.SetActive(true);
    11. restartButtonText.text = "Try Again\n(Click Or Press R)";
    12. restartButtonPanel.SetActive(true);
    13.  
    14. canMovePlayers = false;
    15.  
    16. playerMovement.GameOver(); // Kutsu GameOver-metodia CharacterMovement-komponentissa
    17. SetTLRVisibility(true); // Tee TLR-objekti näkyväksi pelin päättyessä
    18.  
    19. // Lopeta taustamusiikin toistaminen
    20. if (themeSong != null)
    21. {
    22.     audioSource.Stop();
    23. }
    24. }
    Perhaps something like this, so that it plays only once(before you set the isGameEnded to true)
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Either set a boolean when you play it, or else query the AudioSource itself and check if it is playing. See docs for AudioSource for the specific property to test.