- Home /
Walking sound changing on surface
Hey Unity users, I wanted to redo my question since last time. I kinda forgot to include the question in that one, sorry it was my first post. But anyway I am making a horror game and want the walking sound to change when I move form grass to gravel. I want the sound effect to change. The script works as far as compiler errors. TRge only problem is when I enter the collision box to mark the gravel sound, the grass sound just keeps playing and the gravel sound never starts. Please help. This is my code:
#pragma strict
var Sound : AudioClip;
var Sound2 : AudioClip;
function Update () {
if(Input.GetKeyDown("w")){
audio.clip = Sound;
audio.Play();
}
if(Input.GetKeyUp("w")){
audio.Stop();
}
}
function OnCollisionEnter(collision : Collision){
if(Input.GetKeyDown("w")){
}
if(collision.gameObject.tag == "Gravel"){
audio.Stop();
audio.clip = Sound2;
audio.Play();
}
else if(Input.GetKeyUp("w")){
audio.Stop();
}
}
in future, please format your code by highlighting then clicking the 101010 button, and use better tags. Alucard Jay
You really should be editing that question ins$$anonymous$$d of asking a new one. That is the reason you were downvoted. Now you run the risk of being downvoted again for asking a duplicate question, as well as not formatting your code correctly. Please edit your other question with all this information, then delete this question before you get downvoted, ok. If you do, I will upvote that other question.
Edit : Ok, too late now, it looks like we have a duplicate question situation.
http://answers.unity3d.com/questions/489725/creating-a-walk-sound-that-changes-depending-on-th.html
Answer by Kiloblargh · Jul 10, 2013 at 07:12 PM
Because Input.GetKeyDown is only true for one frame. ( It says so right there in the first sentence, if you had just RTFM.) The code you posted will only change the sound to gravel if you hit "w" at exactly the same time as you first touch a gravel object. If you managed to do that, and then hit w again, it would change back to the original sound, because OnCollisionEnter is also only true one frame and Update happens every frame.
Also, never capitalize a variable name.
Ok I changed the code. But now theres a compilier error that says " An instance of "UnityEngine.Coomponet" is required to acess a non static member 'gameObject'." #pragma strict var Sound : AudioClip; var Sound2 : AudioClip;
function Update () {
if(Input.Get$$anonymous$$eyDown("w")){
audio.clip = Sound;
audio.Play();
}
if(Collider.gameObject.tag == "Gravel"){
audio.Stop();
audio.clip = Sound2;
audio.Play();
}
if(Input.Get$$anonymous$$eyUp("w")){
audio.Stop();
}
}
Change the line if(Collider.gameObject.tag == "Gravel")
to this: if(Collider.GameObject.tag == "Gravel")