- Home /
Adding sound javascript in unity2d
I am trying to add sound with javascript in my unity game. but it does not work. i have audio source attached to gameobject as well. i want to sound to play when gameobject collides with another gameobject then it should play sound. i do not know hat is wrong with my code/ i would be greatful if someone helps in adding sound. Below is my code that i am trying to add sound to
Thanks. :)
var Cherrypoint : int = 10;
var pickupSound : AudioClip;
function OnCollisionEnter2D(coll: Collision2D) {
if (coll.gameObject.tag == "Player")
Score_Fruitcatch.Fruitscore += Cherrypoint ;
//Debug.Log("destroyed");
audio.Play();
Destroy(gameObject);
}
Answer by robertbu · Mar 13, 2014 at 05:03 PM
It does not work because on line 15 you are destroying this script and therefore the audio source. If you only want a certain time period of sound, you can do something like this:
if (coll.gameObject.tag == "Player") {
Score_Fruitcatch.Fruitscore += Cherrypoint ;
renderer.enabled = false;
collider2D.enabled = false;
audio.Play();
Destroy(gameObject, 4.0);
}
This will hide the game object and turn off its collider, but the Destory will happen 4 seconds in the future. Set 4.0 to however much time you want to have to play your sound.
it works. but there is another problem. when that certain object collides with any another gameobject it still produces sound. i only want to play when it collides with gameobject tagged player.
The code above was missing a '{' on the first line. I fixed it (and it will fix your issue). But that means you have an extra '{' in your existing code.