- Home /
Play sound on collision doesnt work
I watched like a million tutorials on youtube and every single one is the same, though it doesn't work for me
public class PickUpSound : MonoBehaviour {
public AudioClip[] audioClip;
void PlaySound(int clip)
{
audio.clip = audioClip[clip];
audio.Play();
}
void OnTrigerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
PlaySound(1);
}
}
} Now I did put an audio source on the object I put the script on, and I put the sound I want to play on collision and nothing works :( What should I do? Or do I have to make a completely new script? Thanks in advance
Answer by jebemti · Feb 20, 2016 at 10:10 AM
It's possible you are using an incorrect function.
Check your collider and if it doesn't say "Is Trigger" Use OnCollisionEnter instead.
void OnCollisionEnter(Collision col)
{
if (col.gameObject.CompareTag("Player"))
{
PlaySound(1);
}
}
The other possibility is that you are using audio, which, depending on which version of Unity you are running, has become outdated. If that's the case cache the AudioSource.
AudioSource audioSource;
void Awake(){
audioSource = GetComponent<AudioSource> ();
}
Answer by hexagonius · Feb 20, 2016 at 02:35 AM
missing a "g" in "Trigger"?
Well that was dumb on my side xD Now I get another error saying "IndexOutOfRangeException: Array index is out of range." And it brings me to GetComponent().clip = pickUpSound[clip];
Now when I went back into unity a message popped up saying that it's incorrect and it can fix it for me, therefore it turned audio.clip = audioClip[clip]; audio.Play(); into
GetComponent().clip = pickUpSound[clip]; GetComponent().Play(); Should I make this as it was before or leave it like this? Honestly I don't even know what's wrong in there
Answer by Mokenister · Feb 20, 2016 at 03:06 AM
I was missing an "g" in "Trigger", but now I fixed it and everything should work normally, but when I pick up the object the sound doesn't go off. No error messages pop up, nothing. What's going on? Seems like I kinda fixed the problem but now the sound just doesn't play even though the background music does