4
\$\begingroup\$

I have a music sound clip simply drag-n-dropped to my hierarchy. I also have other sound effects in my game. I want to pause/play background music on button press but only music, not all sound effects. How can I reach this music GameObject in C# code?

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

You can access any object in your hierarchy by searching for it:

GameObject soundObject = GameObject.Find("BackgroundSoundObjectName");

Then you're likely going to want to access the AudioSource component:

AudioSource audioSource = soundObject.GetComponent<AudioSource>();

Then you can use the Pause() and Play() methods of the audio source to control the music.

\$\endgroup\$
2
\$\begingroup\$

If you have multiple audio sources, FindObjectsOfType might be useful (The UnityEngine.Object part is unnecessary if called from a MonoBehaviour-inherited script):

AudioSource[] allAudioSources =
    UnityEngine.Object.FindObjectsOfType<AudioSource>();
\$\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.