- Home /
Gather AudioSources in an Array?
Hi Unity,
I'm making a game right now with 3 scenes:
Splash/MainMenu
Options
Game
So, I would like the options scene to give the player a chance to edit simple settings such as volume, render settings, etc.
I have created a GameObject called "Options" and placed it in the Splash/MainMenu scene, and set DontDestroyOnLoad in the start function, so this should persist through my scenes if I assume correctly.
I would like to create some audio sliders and set the volume of every single AudioSource in the current scene to that float, but I'm confused on how to capture these in an array/list. Which would be easier/more efficient, and how should I capture them?
Thanks! Addyarb
Good point! Would this work as well in the multiplayer version of my game?
Also, how would one go about editing the receiving volume of an Audio Listener?
Answer by TwixEmma · Sep 23, 2014 at 01:55 AM
You can do this to get all the audio sources in your scene:
C#
AudioSource[] audioSources = Object.FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
JS
var audioSources = Object.FindObjectsOfType(AudioSource);
EDIT: Answer updated to reflect comments, thanks for the feedback I don't natively code JS myself.
FindObjectsOfType returns the type in JS, actually (despite what the docs imply), so casting is unnecessary. Nor do you need to use Object since Object is the base class for everything anyway. This is fine:
var audioSources = FindObjectsOfType(AudioSource);
Are you saying in C# you need to create an array but in JS you don't?
What? No. I don't understand that question. :) FindObjectsOfType returns an array; which language you use has nothing to do with it.