One of the two sound stop while other one is playing.

Hello,

I have sound problem in my game. There are three sounds on one game objects. And sometimes, while playing the game, the game object needs to use two sound in same time, but it can’t use them in same time. Unity stops one of them and let the other one plays. And the other one should also keep playing when necessary in that time either but it is stopped by unity. What should i do to manage these sounds? Here is example codes of sounds that i used.

public AudioClip audioClip;

  void PlaySound(int clip)
{
	audio.clip = audioClip[clip];
	audio.Play ();
}

  void Die()
{
	PlaySound(0);
	
	isDead = true;
}

}

I’ve had success with using the PlayOneShot() method of the AudioSource.

Sample Code:

private AudioSource audio;
public AudioClip firstClip;
public AudioClip secondClip;

// in the Inspector window make sure to add each corresponding clip, and obviously have 1 AudioSource component

void Start() {
audio = GetComponent<AudioSource>();
}

void Update() {
if (somethingHappens) {
audio.PlayOneShot(firstClip);
}
if (somethingElseHappens) {
audio.PlayOneShot(secondClip);
}
}

//Hope this helps!

Try set the ‘Priority’ value to 0 from the preferences of AudioSource, or lower value then another audiosource which is less important.

This is because with unity an AudioSource component only deals with a single AudioClip at a time. You can get around this in a few ways, one way is to attach multiple AudioSource components, one for each clip. This method does mean however that you cannot use the audio property of a MonoBehaviour(since that will only get you the first). Instead you can either use a GetComponents() on your Start and store the resulting array. Or you can add the AudioSource components at runtime (one for each clip) in your Start function for example, again store an array of the AudioSources so that you can easily know which source corresponds to which clip. Here is an example script (NOTE: untested but should be ok)

using UnityEngine;

public class MyClass : MonoBehaviour
{
    public AudioClip[] audioClips;
    public bool isDead { get; private set; }

    private AudioSource[] _sources;

    void Awake()
    {
        _sources = new AudioSource[audioClips.Length];
        for (int i = 0; i < audioClips.Length; i++)
        {
            _sources *= gameObject.AddComponent<AudioSource>();*

sources.clip = audioClips*;
// set up the properties such as distance for 3d sounds here if you need to.
}
}*_

public void PlaySound(int clipIdx)
{
if (clipIdx >= 0 && clipIdx < _sources.Length)
_sources[clipIdx].Play();
}

private void Die()
{
PlaySound(0);
isDead = true;
}
}