I placed a health pickup item in the scene. When the player 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 player 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. What could be causing this issue?
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);
}
}
}
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.
Thank you so much!!!
Your AudioSource is attached to the object which has your HP1 component. In your code where you trigger the audio to play, you say
Destroy(gameObject);
at the same time. As a result, there is no more AudioSource around to play the clip you're trying to play.
A solution would be to have the object live long enough to play the clip. Say if you're adding some visual effect anyway, just time it to live long enough for the clip to play as well.
Another option is to have (or even instantiate) one more more dedicated GameObjects with an AudioSource which you put in the spot where your object was, and have it play the audio clip.