basicly i mostly copied code from tutorial but i have problem with sounds canceling after another sound plays. for example when i shoot and play sound if i hit enemy and explosion sound plays shooting sound gets muted. i already have this script on empty gameobject soundmanager and access it through soundmanager.instance.playSingle(sound). i dont know what else to do to make sounds not cancel each other! any help is appreciated

void Awake()
{
    //Check if there is already an instance of SoundManager
    if (instance == null)
        //if not, set it to this.
        instance = this;
    //If instance already exists:
    else if (instance != this)
        //Destroy this, this enforces our singleton pattern so there can only be one instance of SoundManager.
        Destroy(gameObject);

    //Set SoundManager to DontDestroyOnLoad so that it won't be destroyed when reloading our scene.
    DontDestroyOnLoad(gameObject);
}


//Used to play single sound clips.
public void PlaySingle(AudioClip clip)
{
    //Set the clip of our efxSource audio source to the clip passed in as a parameter.
    efxSource.clip = clip;

    //Play the clip.
    efxSource.PlayOneShot(efxSource.clip);
}
public void PlayCrash(AudioClip clip)
{
    //Set the clip of our efxSource audio source to the clip passed in as a parameter.
    crashSource.clip = clip;

    //Play the clip.
    crashSource.PlayOneShot(crashSource.clip);
}

public void PlayShoot(AudioClip clip)
{
    //Set the clip of our efxSource audio source to the clip passed in as a parameter.
    ShootSource.clip = clip;

    //Play the clip.
    // ShootSource.PlayOneShot();
    ShootSource.PlayOneShot(ShootSource.clip);
}

//RandomizeSfx chooses randomly between various audio clips and slightly changes their pitch.
public void RandomizeSfx(params AudioClip[] clips)
{
    //Generate a random number between 0 and the length of our array of clips passed in.
    int randomIndex = Random.Range(0, clips.Length);

    //Choose a random pitch to play back our clip at between our high and low pitch ranges.
    float randomPitch = Random.Range(lowPitchRange, highPitchRange);

    //Set the pitch of the audio source to the randomly chosen pitch.
    efxSource.pitch = randomPitch;

    //Set the clip to the clip at our randomly chosen index.
    efxSource.clip = clips[randomIndex];

    //Play the clip.
    efxSource.Play();
}

}

1 Answers

0
Immorality On

You need to either create a seperate audiosource that handles the explosions (maybe on a projectile object/ class), or if you don't need anything fancy, you could use AudioSource.PlayClipAtPoint(). See docs.

So to put it into action, you would modify your PlayCrash method to accept the position where to play the crash (or if it doesn't matter, just use Vector3.Zero

public void PlayCrash(AudioClip clip, Vector3 location)
{
    AudioSource.PlayClipAtPoint(clip, location);
}