- Home /
audio on collision
I want to have an audio play when an object collides into somthing. what would the script look like? Here is my code, please tell me how to do this.
var sound: //unkown;
function OnCollisionEnter (collision: Collision) {
if (collision.gameObject.name == "win") {
sound.play();
}
}
Answer by by0log1c · Sep 07, 2012 at 04:38 AM
Assuming there's already an AudioClip linked to the gameObject AudioSource component in the Inspector... well then it should be an AudioSource, yeah:
var sound:AudioSource; //don't forget to link it in the Inspector
function OnCollisionEnter (collision: Collision)
{
if (collision.gameObject.name == "win")
{
sound.Play();
}
}
It still does not work it has an error that says: The name 'Sound' does not denote a valid type ('not found'). I am using the code above.
when ever I try to assign the script to an object it say: All compiler errors have to be fixed first. And it is still having the same error as above. I also tried the P. Don't I have to have it assigned to an object before I can assign somthing to the variable?
The sound variable just create a slot in the Inspector for you to drag an AudioSource component that you've added to a GameObject. Once its linked, make sure you have an AudioClip linked into that AudioSource component. Only then would it work. Though with the 'Play' correction from the patient @Fattie cough, there shouldn't be compilation errors, so its probably elsewhere in your code.
Your answer
Follow this Question
Related Questions
Collider isTrigger for audio clip lets me pass through object. How to fix? 0 Answers
Audio Script 1 Answer
Play Animation OnTriggerEnter 2 Answers
Sound is stopping prematurely (Read Description) 0 Answers
Audio not playing on collision 0 Answers