Sound is not playing from Script
Hey guys im really new to Unity and i hope my Question is not that dump but i already tested much out and i dont know something else to do.
i created a Healthpotion, dropped by Enemies, and i want to include a drinking sound after collecting it. My Script:
public Animator anim;
public int healAmount;
public AudioSource drinkSound;
PlayerHealth playerScript;
void Start()
{
anim = GetComponent<Animator>();
anim.SetBool("Potion", true);
playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
}
private void OnTriggerEnter (Collider collision)
{
if (collision.tag == "Player")
{
drinkSound.Play();
playerScript.Heal(healAmount);
Destroy(gameObject);
}
}
I also created a Audiosource on the Prefap with my Sound and put it on the Script Options. If i select "Playing on Awake" at the Audiosorce, the sound works perfectly but not when i collect the potion.
$$anonymous$$aybe the audiosource is far from the audiolistener (camera)?
Answer by jimmiewalker653 · Nov 26, 2020 at 03:22 PM
You'll need to call the AudioSource. I've updated your code for you. So in this code, I've added an AudioSource, called it in the Start method group, then I'm telling Unity to use the Drinking audio clip to play. Lastly, I tell the AudioSource to play that clip. This is why the clip is first, then the AudioSource is told to play the sound.
public AudioSource a_Audio;
public AudioClip DrinkSound;
void Start()
{
anim = GetComponent<Animator>();
anim.SetBool("Potion", true);
a_Audio = a_Audio.GetComponent<AudioSource>();
playerScript = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
}
private void OnTriggerEnter (Collider collision)
{
if (collision.tag == "Player")
{
a_Audio.clip = DrinkSound;
a_Audio.Play();
playerScript.Heal(healAmount);
Destroy(gameObject);
}
}