2
\$\begingroup\$

I want access to (for example) all AudioSources in Unity and stop all sounds.

using UnityEngine;
using System.Collections;

public class StopAllSound: MonoBehaviour {

    void Start() {
        AudioSource[] allMyAudioSources = GetComponents<AudioSource>();
        allMyAudioSources.Stop();
    }
}

This does not work, because of the followin error:

Assets/SlowMotion.cs(8,35): error CS1061: Type `UnityEngine.AudioSource[]' does not contain a definition for `Stop' and no extension method `Stop' of type `UnityEngine.AudioSource[]' could be found (are you missing a using directive or an assembly reference?)

I try it by FindObjectsOfType:

using UnityEngine;
using System.Collections;

public class SlowMotion : MonoBehaviour {

    void Start() {
        AudioSource[] allAudioSources = UnityEngine.Object.FindObjectsOfType<AudioSource>();
        allAudioSources.Stop();
    }
}

but I get the same error.

\$\endgroup\$
5
\$\begingroup\$

Because Array doesn't contains Stop. But AudioSource does. So take all AudioSources in loop and Stop them as AudioSource not AudioSource[]. Array of anything having its own attributes and methods irrespective of what type of element that array contains.

You can do that by,

using UnityEngine;
using System.Collections;

public class StopAllSound: MonoBehaviour {

    void Start() {
        AudioSource[] allMyAudioSources = FindObjectsOfType<AudioSource>();
        foreach(AudioSource s in allMyAudioSources)
            s.Stop();
    }
}
\$\endgroup\$
1
\$\begingroup\$

If you want to mute all sounds in your game, then it might be far more elegant to not mute your audio sources but mute the AudioListener instead. You can do this with AudioListener.pause = true or AudioListener.volume = 0.0f.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.