bdotalex

I redid this script to be a little cleaner, and have better comments and stuff. Note that this will work for any events that get overlapped for whatever reason, not just audio stuff. Also, as Pharan said, this works for pretty much any other program, not just Spine-Unity.
using UnityEngine;

public class MecanimEvents : MonoBehaviour
{

#region Variables

[Header("Audio Event Variables")]
public AudioSource footstepAudioSource; // drop the audio source that has your footstep sound into this slot in the inspector
public float soundWait = 0.1f; // window to block duplicate events in seconds

private float timer = 0f;
private bool audioOK = false;
private bool footstepAudioEvent = false;

#endregion

void Update()
{

#region Audio Events

// if not ok to play another sound
if (audioOK == false)
{
// start keeping track of the amount of time since the audio source last started playing a sound
timer += Time.deltaTime;
}

// if enough time has passed since the audio source last started playing a sound, and we haven't already noted that the audio source is ok to play another sound...
if (timer >= soundWait && audioOK != true)
{
// note that the audio source is ok to play another sound now
audioOK = true;
}

// if the audio source is ok to play another sound now, and a footstep audio event is recieved...
if (audioOK == true && footstepAudioEvent == true)
{
// stop any footstep sound that might be still playing
footstepAudioSource.Stop();
// play a new footstep sound
footstepAudioSource.Play();
// reset the amount of time since the audio source last started playing a sound
timer = 0f;
// note that it is now not ok to play another sound
audioOK = false;
// note that there is no longer an audio event coming in (this one is used up)
footstepAudioEvent = false;
}
// if the audio source was not ok to play another sound, and we havent already noted that there is no longer an audio event coming in...
else if (footstepAudioEvent != false)
{
// note that there is no longer an audio event coming in (throw the event out, as it came in too fast)
footstepAudioEvent = false;
}

#endregion

}

#region Functions

// getting incoming footstep events from mecanim
void footstep()
{
// noting that a footstep audio event has been recieved
footstepAudioEvent = true;
}

#endregion

}
bdotalex
Posts: 2

Pharan

Thanks for sharing.
And its applicable even if you're not using Spine, so that's cool too!
User avatar
Pharan

Pharan
Posts: 4444


Return to Unity