I recently decided to try to create a class which is (essentially) a song manager which would ideally allow me to create and manipulate songs to be different between each “loop” or change the song through the use of various triggers. Unfortunately, I ran into a bit of a snag – the audio source components I attached to base object do not want to play.
I’ll go step by step through the code:
public AudioSource[] trackArray = new AudioSource[4];
public float[] trackVolumeArray = new float[4];
public float allTrackVolumeScale = 100.0f;
public bool bClampValues = true;
private int totalIndexOfVolumeArray;
private int totalIndexOfTracksArray;
Nothing special here, I then initialize the variables in the Start():
void Start ()
{
int trackArrayIndex = 0;
int volumeArrayIndex = 0;
// Initialize the Audio Source files..
foreach( AudioSource track in trackArray )
{
trackArray[trackArrayIndex] = gameObject.AddComponent ("AudioSource") as AudioSource;
track.volume = 1f;
track.enabled = true;
trackArrayIndex++;
}
// Initialize the Volume Settings..
foreach( float trackVolume in trackVolumeArray )
{
trackVolumeArray[volumeArrayIndex] = 100f;
volumeArrayIndex++;
}
totalIndexOfTracksArray = trackArrayIndex;
totalIndexOfVolumeArray = volumeArrayIndex;
}
Side Note: Earlier I tried to set each float by referring to it as “trackVolume” to no success, since you cannot redefine it. Is it wrong to use a foreach and not actually use each component your referencing?
Lastly, in the update function, I call a “check playing” function, which for testing purposes I had to change to try to be more direct with no results. The ideal way of doing this would probably be another “foreach”.
private void CheckPlaying()
{
if( trackArray[0].isPlaying != true )
{
trackArray[0].Play();
}
if( trackArray[1].isPlaying != true )
{
trackArray[1].Play();
}
}
I should also tell you that the AudioSource array has inputs in the inspector, and all I did from there is reference a audiosource that exists in the scene and is a child of the SongManager game object. Obviously, those AudioSources have an AudioClip attatched to them.
Is there any reason why this wouldn’t be working?