2

DISCLAIMER : This question was for a school project that was not finished because of this bug. The project being over, proposition for future developers can be done but I can't validate any of the answers as I don't have access to the source code anymore.

I'm currently creating a drum simulation for a school project using HTC Vive and Unity 3D.

In order to do that, I used a BoxCollider on the toms and the method :

void OnCollisionEnter(Collision col)
{
   GetComponent<AudioSource>().Play();         
}

So that the sound plays when the HTC Vive remote touches a tom. The trouble is that the sound keeps playing as long as the remote touches the tom instead of playing once on collision.

I also tried the OnTriggerEnter() method with the same result.

sh5164
  • 276
  • 2
  • 15
  • Check if the Loop option is marked checked in the Audio Source, if so then uncheck it. You should be fine. Also check the audio file itself if it is large or small just looping again and again. – Pratham Sehgal May 16 '17 at 11:47
  • @PrathamSehgal Thanks for the comment, but the project on which I was working is over now, so I'll close this question. – sh5164 May 16 '17 at 12:13

2 Answers2

0

create an bool variable and use it to control play only once.

bool isPlaying = false;//defined somewhere
void OnCollisionEnter(Collision col)
{
   if (!isPlaying)
   {
     GetComponent<AudioSource>().Play();         
     isPlaying = true;
   }
}
navylover
  • 12,383
  • 5
  • 28
  • 41
  • I thought about that, though that will allow the sound to be played once in all the simulation instead of once on collision, except if there's a way to set it back to "false" at the right time. – sh5164 Feb 01 '17 at 11:50
  • u might set it back to false when controller leaves the tom – navylover Feb 01 '17 at 12:06
0

You could use a Coroutine to not allow the sound to be repeated for the duration of the sound clip.

void OnCollisionEnter(Collision col)
{
    if(!isPlaying)
    {
        AudioSource audio = GetComponent<AudioSource>();
        audio.Play();
        StartCoroutine(FinishSound(audio.clip.length));
    }
}

void OnCollisionExit(Collision col)
{
    isPlaying = false;
}

IEnumerator FinishSound(float l)
{
    yield return new WaitForSeconds(l);        
    isPlaying = false;        
}
Liam Ferris
  • 1,786
  • 2
  • 18
  • 38