- Home /
Footsteps... Please Help
I am trying to create a js script that plays a random footstep sound when I'm on a particular surface, like gravel or metal, but everything I try doesn't work. I have searched the forums and not found anything.
This is what I have already got.
var WalkSoundInterval:float = 0.5;
var FootstepsVolume:float = 0.5;
var FootstepSoundsNormal:AudioClip[];
var FootstepSoundsGravel:AudioClip[];
var FootstepSoundMetal:AudioClip[];
InvokeRepeating("UpdateInterval",0,WalkSoundInterval);
function UpdateInterval()
{
if(Input.GetKey("w"))
{
audio.clip = FootstepSoundsNormal[Random.Range(0,FootstepSoundsNormal.length)];
audio.volume = FootstepsVolume;
audio.PlayOneShot(audio.clip);
}
}
I have tried using the OnCollisionEnter to switch a boolean to true, but that didn't work and nothing else I try works. Please help.
Thanks in advance.
Answer by TonyLi · Apr 03, 2013 at 01:19 PM
You can create a trigger collider that encompasses each surface area. For example, say you have a wood-floored room and a gravel beach. Create an empty game object with a box collider that covers the entire room, check Is Trigger, and set the Tag to "wood". Do the same for the beach, but set the Tag to "gravel".
In your character's script, add code similar to this:
var surface = "normal";
function OnTriggerEnter(other : Collider) {
surface = other.tag;
}
function UpdateInterval() {
if (Input.GetKey(KeyCode.W)) {
if (surface == "wood") audio.clip = FootstepSoundsWood[...]
else if (surface == "gravel") audio.clip = FootstepSoundsGravel[...]
else audio.clip = FootstepSoundsNormal[...]
audio.PlayOneShot(audio.clip);
...
}
}
Obviously that's pseudocode above and not directly compilable. It uses the collider's tag to define the surface type, but you can certainly do something different like using layers or attaching a component that defines the surface type. And instead of a long sequence of "if (surface == "x") else..." statement, you could use a lookup table (e.g., "audio.clip = LookupTable[surface]").
Your answer
![](https://koobas.hobune.stream/wayback/20220613095618im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Sound on collision 3 Answers
Getting audio to play on collision 3 Answers
Audio Script 1 Answer