Duplicate Question
Play audio on Hit
Hi, I want to play the audio of an object when my player hits it. For example, my player when hits the object, the sound of that object plays 1 time and my player collects 1 point from it. I know the point collection but the sound ain't playing when my player hits it.
Could you show your (relevant) code so we can see what you tried?
I am trying to do the same thing with my coins. When The player touches the coin, it is supposed to play the sound and then set the coin to Active(false). Is the code just not giving the audio clip enough time to finish before it becomes inactive?
This information is in the manual and has been answered many times.
Answer by JoshDangIt · May 10, 2016 at 04:32 PM
Simplest way is to call AudioSource.PlayClipAtPoint().
http://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
Answer by Ali-hatem · May 10, 2016 at 05:14 PM
@SaintTippu you can simply attach the audio source to the player & change the clip as needed when collide with something @aballif to avoid playing desabled AudioSource when deactivating object that hold the sound :
public AudioClip coin;
public AudioClip wall;
AudioSource audio;
void Start(){
audio = GetComponent<AudioSource>();
}
void OnCollisionEnter(Collision other){
if(other.gameObject.tag == "coin"){
audio.clip = coin;
audio.Play();
}
if(other.gameObject.tag == "wall"){
audio.clip = wall;
audio.Play();
}
}
& make sure objects have collider attached & Rigidbody so colliders work fine & if it's trigger colliders use OnTriggerEnter & if it's 2D project use OnCollisionEnter2D or OnTriggerEnter2D & lastly you can vice-versa because you can't play desabled AudioSource.
If I only have One audio clip for the object, can I leave of the Public AudioClips and leave of the audio.clip = coin?
yes just call audio.Play();if you have attached the clip to the AudioSource in inspector no need to declare any AudioClip . & the reason i did that because that's why many people ad each AudioSource to each game object so thy can have player audio & enemy audio etc... but this way have a trouble when desabling the object that holds the audio
Follow this Question
Related Questions
Footstep sound does not finish playing, it keeps restarting on movement 0 Answers
Second AudioClip won't play 0 Answers
How can I make my audio work for both headphones and computer/laptop speakers? 0 Answers
How to control by code a set of speakers connected to Unity? 0 Answers
Is there a way to get the audio form mobile mic and find it's music key ? Like in a karaoke game. 0 Answers