Footsteps via script

Hello,

I know this has been questioned many times as I’ve read majority of the posts regarding this, so I coded a footstep script in C# which works to some extent but the audio plays like crazy if you know what I mean? Example you walk on a certain texture on the terrain, it plays but very fast when walking but say you took a baby step at a time it plays fine which you would expect anyway. I have put a few checks in to stop it playing when the Rigidbody is sleeping or if the Character Controller is not grounded and vice versa.

Here’s the script:

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]

public class FootstepManager : MonoBehaviour
{

    private AudioSource m_Audio;
    public AudioClip[] _GrassSounds;
    public AudioClip[] _MudSounds;
    public AudioClip[] _GravelSounds;
    public CharacterController _CharController;
    private Rigidbody _RigBod;
    private bool playSteps;

    void Awake()
    {
        m_Audio = gameObject.AddComponent<AudioSource>();
        _RigBod = _CharController.GetComponent<Rigidbody>();
    }

    void Start()
    {
        StartCoroutine(PlayFootstep());
        playSteps = true;
    }

    void Update()
    {
        if (!_CharController.isGrounded && playSteps)
        {
            playSteps = false;
            StopCoroutine(PlayFootstep());
        }
        else if (_CharController.isGrounded && !playSteps && _CharController.velocity.magnitude > 0.2f)
        {
            StartCoroutine(PlayFootstep());
        }
    }


    IEnumerator PlayFootstep()
    {
        int curSplatIndex = TerrainSurface.GetMainTexture(transform.position);

            switch (curSplatIndex)
            {
                case 0:
                   yield return new WaitForSeconds(0.4f);
                   m_Audio.PlayOneShot(_GrassSounds[Random.Range(0, _GrassSounds.Length - 1)]);                   
                   break;
                case 1:
                    m_Audio.PlayOneShot(_GravelSounds[Random.Range(0, _GravelSounds.Length - 1)]);
                    break;
                case 2:
                    m_Audio.PlayOneShot(_MudSounds[Random.Range(0, _MudSounds.Length - 1)]);
                    break;
            }
        }

    }

I have tried many ways of trying to solve this but to no 'avail, hopefully someone can point me in the right direction!

Thanks in advance!

@benny279

if its an mecanin animation clip than you can use events for playing the footsteps sound.

@benny279 I recorded a video tutorial on how to do this, and also included my script for free. Check it out, if you’re still looking for a solution.