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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to destroy sound when second press key?

Discussion in 'Scripting' started by UMURAS, Sep 3, 2019.

  1. UMURAS

    UMURAS

    Joined:
    Jun 15, 2019
    Posts:
    18
    When I press the first key on the keyboard, the audio file works, but the second time I press it, I want to close the current audio file and start over again.

    public class Play : MonoBehaviour
    {
    public AudioClip sound;
    AudioSource aSource;

    void Start()
    {
    aSource = GetComponent<AudioSource>();
    }


    void Update()
    {
    if (Input.GetKeyDown(KeyCode.H))
    {
    if (aSource.isPlaying == false)
    {
    aSource.PlayOneShot(sound);
    }

    }
    }
     
  2. Neriad

    Neriad

    Joined:
    Feb 12, 2016
    Posts:
    125
    Code (CSharp):
    1.         // Second input
    2.         if (Input.GetKeyDown(KeyCode.A))
    3.         {
    4.             if (aSource.isPlaying)
    5.             {
    6.                 aSource.Stop();
    7.                 aSource.PlayOneShot(sound);
    8.             }
    9.         }
    This should work.
     
  3. UMURAS

    UMURAS

    Joined:
    Jun 15, 2019
    Posts:
    18
    Thank you very much. It is worked