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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Making a sound effect play a single time on collision

Discussion in 'Scripting' started by TurduckenMan, May 29, 2014.

  1. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Code (csharp):
    1.     void OnTriggerEnter2D(Collider2D collider)  {
    2.        
    3.         if (collider.tag == "ScoreBox") {
    4.             audio.Play ();
    5. }
    6. }
    Basically I want a sound effect to play when my player collides with a box collider. It's working, however the sound continues to loop even though I have the sound effect set to not loop. The sound is in an audio source which is in the player, and I tried "PlayOneShot" but was fairly confused by it. So if that's what I should be using, some explanation to it and how exactly I'd implement it in the code would be awesome. :)

    Thanks!
     
  2. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Would really love some help, I feel like it's a simple solution and I'm just lacking the knowledge haha.
     
  3. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Try :

    Code (csharp):
    1.  
    2. audio.PlayOneShot(YourSound);
    3.  
     
  4. DarkArts-Studios

    DarkArts-Studios

    Joined:
    May 2, 2013
    Posts:
    389
    You can either do as Intense_Gamer94 suggested before my reply, in which case you will need to specify your AudioClip on each call, or simply (within Start) set the following:

    Code (csharp):
    1. audio.loop = false;
    ... and then use your code as is.

    I hope this helps.

    Reference: AudioSource.loop
     
    Last edited: May 29, 2014
  5. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Thanks, works perfectly! If I wanted to do it the way Intense Gamer said however, how exactly do I specify the audio clip?

    By that I mean what do I type and where?
     
  6. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    By doing something like this :
    Code (csharp):
    1.  
    2. //JS
    3.  
    4. var mySound : AudioClip;
    5.  
    6. function OnTriggerEnter2D(collider : Collider2D)  {
    7.  
    8. if (collider.tag == "ScoreBox") {
    9.  
    10. audio.PlayOneShot (mySound);
    11.  
    12. }
    13. }
    14.  
    15.  
     
  7. TurduckenMan

    TurduckenMan

    Joined:
    Apr 20, 2014
    Posts:
    29
    Nevermind I figured it out haha
     
    Last edited: Jun 7, 2014