I placed a health pickup item in the scene. When the main character collides with the item, a pickup sound effect is supposed to play. The issue I’m facing is that if I check “Play on Awake,” I can hear the sound, but when the character actually picks up the item, I can’t hear the sound effect. I used Debug.Log to confirm that the code for playing the audio is indeed executing.
The item disappears correctly, and the health value increases as expected upon pickup.
I’ve ensured that:
- The audio volume is not set to zero.
- The scene is not muted.
- In the same scene, I can hear the weapon sound effects when I use them.
What could be causing this issue? Thank you sooooo much!
public class HP1 : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip pickupSound;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.GetComponent<Player>())
{
audioSource.Play();
Player.HP++;
Player.HPChangeEvent.Invoke();
Destroy(gameObject);
}
}
}
First thing I would consider is if the AudioSource is physically far away from the listener: you have not checked Bypass Listener Effects above so distance will attenuate the volume quite a lot.
Second would be if the AudioSource is on this GameObject because you destroy it, which would cause you to hear nothing.
If it’s not that… Sounds like you wrote a bug… and that means… time to start debugging!
By debugging you can find out exactly what your program is doing so you can fix it.
Use the above techniques to get the information you need in order to reason about what the problem is.
You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
I found out what the problem was and wrote it out for others who had the same problem: The reason was that the audio was too short and the item was destroyed before the audio could play.
The solution was to have the item destroyed after the audio played, by changing it to Destroy(gameObject, pickUpSound);
Or use:
private IEnumerator GetHP1()
{
yield return new WaitForSeconds(pickUpSound.length);
Destroy(gameObject);
}
The best solution is to put the audio on the player or create an empty object that won’t be destroyed, just for all the audio
1 Like