aciko11
aciko11

Reputation: 65

Unity animations event with blend tree sounds overlapping

I have a simple 2d blend tree with 4 animations, each of these has 2 animations event, all with the same name: Step. The funcion Step() on the script plays a footstep sound. My problem is that the sounds overlap. How do i solve this?

Upvotes: 1

Views: 2549

Answers (3)

vilkoivshchi
vilkoivshchi

Reputation: 21

You can split steps events along Z and X axis. When your char move along Z axis, invoke one method, if char move along X axis - another one method. You get speeds along Z and X axes and make some logic like in code bellow.

I have 2d blend tree and 4 animation clips and in my case code look like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class FootstepSound : MonoBehaviour
{

public AudioClip leftStep, rightStep;
[Range(0, 1f)]
public float footStepsVolume = 1f;
private AudioSource _audioSource;
Animator _anim;


private void Start()
{
    _audioSource = GetComponent<AudioSource>();
    _anim = GetComponent<Animator>();
    
}
public void stepLeft()
{

    if (_anim.GetFloat("DeltaX") == 0 && _anim.GetFloat("DeltaZ") != 0)
        _audioSource.PlayOneShot(leftStep, footStepsVolume);

}
public void stepRight()
{
    if (_anim.GetFloat("DeltaX") == 0 && _anim.GetFloat("DeltaZ") != 0)
        _audioSource.PlayOneShot(rightStep, footStepsVolume);
}
public void strafeLeft()
{
    if (_anim.GetFloat("DeltaX") != 0)
        _audioSource.PlayOneShot(leftStep, footStepsVolume);

}
public void strafeRight()
{
    if (_anim.GetFloat("DeltaX") != 0)
        _audioSource.PlayOneShot(rightStep, footStepsVolume);
}
}

Upvotes: 1

aciko11
aciko11

Reputation: 65

Ok solved, pretty easy but i was tired and needed the break xD. Simply used an if to allow or not the sound to be played:

if(Time.time - lastTime >= duration)
        {
            lastTime = Time.time;
            FindObjectOfType<AudioManager>().Play("Footstep");
        }

Upvotes: 2

Fay
Fay

Reputation: 122

What do you mean by overlap? If you want the sounds to be played separetely (even if at the same time), you should have more than one AudioSource.

If you want to use the same AudioSource, you'll need to replace the current audio clip or wait the old sound completes to play the new sound (but it will play out of sync with animation).

Upvotes: 0

Related Questions