Sound on collision.
Im new to unity and need to have a sound play when my projectile hits the target except nearly all code i try fails. if someone could give a simple solution and go through it that would really help.
Answer by mrlafle · Nov 30, 2015 at 04:51 AM
Here's what you can do with Javascript.
#pragma strict
var hit:AudioClip;
function OnCollisionEnter(col:Collision) {
if(col.gameObject.tag == "objectTag"){
audio.PlayOneShot(hit);
}
}
If you attach this code to your projectile (which is what I would do), then "objectTag" would be the tag of your target. But if you wish to attach it to your target instead then use the projectile's tag.
Whatever you attach the script to should also have an Audio Source component. Then just click and drag your .wav audio file into the box next to the Hit variable in your Script component (in the Inspector).
If you're not sure how to assign a tag or add an Audio Source component then just Google it. Also, you may need to be close to the game object to hear the sound. I'm a bit new to Unity also but I hope this helps anyways :D
Edit: just one more thing, if you're destroying the game object on collision then you won't give the Audio Source a chance to play the sound
Ok so i did what you said except it come up with this error. "Assets/Scripts/javasound.js(6,17): BCE0019: 'tag' is not a member of 'UnityEngine.Collision'." do you have a solution?
It was a typo... ins$$anonymous$$d of using col.tag in the if statement, use col.gameObject.tag
Sorry about that! It was late last night