Unity walking sounds (if and buttons error)

2.1k Views Asked by At

Basically, I need a script to play a walking-sound while my player is walking and a running-sound while he's running. Due to how my player is setup it needs to be done with the Input and Keys...

I have this basic script made but it doesn't work too well. The transition from running -> walking -> stop and running -> stop and so on doesn't work consistently or even well. The other problem is pressing shift while standing still also plays the sound. I already tried doing the SHIFT && W || W && SHIFT and it just doesn't work.

Any help would be much appreciated!!

My Foley.cs script:

using UnityEngine;
using System.Collections;

public class Foley : MonoBehaviour {

public AudioClip Footsteps;

public AudioClip RunningSound;

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown(KeyCode.LeftShift) && !audio.isPlaying)
    {
        audio.clip = RunningSound;
        audio.loop = true;
        audio.Play();
    } else if (Input.GetKey(KeyCode.W) && !audio.isPlaying && !Input.GetKey(KeyCode.LeftShift)) {
        audio.clip = Footsteps;
        audio.loop = true;
        audio.Play();           
    }

    if (Input.GetKeyUp(KeyCode.W) && audio.isPlaying)
    {
        audio.Stop();
    }

    if (Input.GetKeyUp(KeyCode.LeftShift) && audio.isPlaying)
    {
        if (Input.GetKey(KeyCode.W)) 
        {
            audio.clip = Footsteps;
            audio.loop = true;
            audio.Play();           
        } else {
            audio.Stop();
        }
    }
}
}
1

There are 1 best solutions below

1
On BEST ANSWER

This script should do basically what you want. On 'w' play walk sound, on w + shift, play run sound.

 #pragma strict

 var walk : AudioClip;
 var run : AudioClip;

 var isWalking : boolean = false;
 var isRunning : boolean = false;


 function Update() 
 {
     GetState();
     PlayAudio();
 }


 function GetState() 
 {
     if ( Input.GetKey(KeyCode.W))
     {
         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();
 }
 }