- Home /
Audiosource.play() sometimes plays sound, most times it doesn't
I'm making a simple pachinko game, and when the ball leaves the bottom of the screen, it hits a trigger and should play a sound during the OnTriggerEnter2D function. The trigger fires every time, but the sound doesn't play.
The function triggers as expected,
Debug.Log(""); fires correctly every time the sound is supposed to be played
The Scene doesn't have the Mute Audio button pressed
The Volume is set to 1, Spacial Blend is 0
It works sometimes, but not always... even though the code prints the correct log every time.
I have tried both audioSource.Play() and PlayOneShot()
I have an audioListener attached to my mainCamera
I'm not destroying the object playing the sound
There are no errors, and nothing is null
The code that I have to play is below:
private void OnTriggerEnter2D(Collider2D collision)
{
if (cat)
{
audioSource.clip = CatAudio;
audioSource.volume = 1.0f;
audioSource.Play();
//audioSource.PlayOneShot(CatAudio);
Debug.Log("Play Cat Sound");
}
else
{
audioSource.clip = DogAudio;
audioSource.volume = 1.0f;
audioSource.Play();
//audioSource.PlayOneShot(DogAudio);
Debug.Log("Play Dog Sound");
}
}
Thanks for all the help!
Update:
If I remove the lines where I change the clip, it plays as expected. So The problem seems to be in the changing of the clips right before trying to play it.
From my understanding of audioSource.PlayOneShot(clip) it should play correctly... and it's not
Answer by binaryprogrammer · Oct 22, 2019 at 06:42 PM
Apparently I lied... My audioclips were null.
I must have added audioclips to a game object instead of my prefab.
Answer by xxmariofer · Oct 22, 2019 at 08:29 AM
try using
AudioSource.PlayClipAtPoint(DogAudio);
I tried this, the results are no different than PlayOneShot(). As a side note, the location of the sound shouldn't matter, it's a 2D sound