So I have two audio files, one for walking and one for sprinting, and I am trying to figure out how to switch between the files depending on if you are walking or sprinting. Here is my script so far:
var walk:AudioClip;
var run:AudioClip;
function Update () {
if ((Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" )) && ((Input.GetKey("left shift") || Input.GetKey("right shift")))){
audio.clip=run;
audio.Play();
}
else if ((Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ))){
audio.clip=walk;
audio.Play();
}
else if ((!Input.GetButtonDown( "Horizontal" ) || !Input.GetButtonDown( "Vertical" ))){
audio.Stop();
}
}
When I attach this it doesn’t play any sound at all, even when I am walking or sprinting. Any ideas why this might be? (By the way I am using the first person character controller)
I think it is playing, just playing from the start at every frame ( audio = foo; audio.Play(); ), therefore you never hear the full sound play.
First problem : Input.GetButtonDown( “Horizontal” ) should be Input.GetAxis( “Horizontal” )
I would break it down into 3 steps : find if the character is walking or running; store that information in booleans; then check if the correct audio is playing (if not, set audio clip) then Play =]
Here is a tested working script :
#pragma strict
var walk : AudioClip;
var run : AudioClip;
var isWalking : boolean = false;
var isRunning : boolean = false;
function Update()
{
GetState();
PlayAudio();
}
function GetState()
{
if ( Input.GetAxis( "Horizontal" ) || Input.GetAxis( "Vertical" ) )
{
if ( Input.GetKey( "left shift" ) || Input.GetKey( "right shift" ) )
{
// Running
isWalking = false;
isRunning = true;
}
else
{
// Walking
isWalking = true;
isRunning = false;
}
}
else
{
// Stopped
isWalking = false;
isRunning = false;
}
}
function PlayAudio()
{
if ( isWalking )
{
if ( audio.clip != walk )
{
audio.Stop();
audio.clip = walk;
}
if ( !audio.isPlaying )
{
audio.Play();
}
}
else if ( isRunning )
{
if ( audio.clip != run )
{
audio.Stop();
audio.clip = run;
}
if ( !audio.isPlaying )
{
audio.Play();
}
}
else
{
audio.Stop();
}
}