Unable to set second AudioSource to loop

Hi,

Using scripting I added a couple of AudioSource components however I found that when I tried to set AudioSource.audio.loop = true I was always changing the value of the first AudioSource. I tried a number of approaches but this kept happening. I created a brand new empty project in Unity 4.2.1 Pro to demonstrate this. I attached the following script to the MainCamera and then hit run, you can see in the inspector that the loop tickbox on the second audio source is unticked when I think it ought to be ticked.

using UnityEngine;
using System.Collections;

public class audiotest : MonoBehaviour {

	private AudioSource musicAudioSource = null;
	private AudioSource ambientAudioSource = null;
	private AudioSource[] audioSources;
	
	void Awake () {
	    musicAudioSource = gameObject.AddComponent<AudioSource>() as AudioSource;
		musicAudioSource.audio.loop = true;
		
	    ambientAudioSource = gameObject.AddComponent<AudioSource>() as AudioSource;
		ambientAudioSource.audio.loop = true;
		
		// NOTE: musicAudioSource is not the same as ambientAudioSource
		//       however setting ambientAudioSource.audio.loop = false
		//       actually changes the loop boolean on the first AudioSource
		
		if (musicAudioSource == ambientAudioSource)
			Debug.Log("musicAudioSource == ambientAudioSource");
		
		// Another approach to try and set all Audio Sources to loop
		audioSources = GetComponents<AudioSource>();
		for(int i=0; i < audioSources.Length; i++)
		{
			audioSources*.audio.loop = true;*
  •  	Debug.Log("Set audio source " + i + " to loop");*
    
  •  }*
    
  •  // Uncomment either of the following two lines and you'll see that*
    
  •  // the first AudioSource's loop boolean is changed.*
    
  •  //ambientAudioSource.audio.loop = false;*
    
  •  //audioSources[1].audio.loop = false;*
    
  • }*
    }
    Have I misunderstood something here or is this a bug in Unity?
    I have worked around this in my project by creating the audio sources in the inspector, ticking their loop checkboxes, and then working with those in scripting.
    Cheers,
    Mark

Don’t use the audio property: audio refers to the first AudioSource attached to the GameObject. You already has the references to all AudioSources: use them directly.

void Awake () {
    musicAudioSource = gameObject.AddComponent<AudioSource>() as AudioSource;
    musicAudioSource.loop = true; // don't use property *audio* !

    ambientAudioSource = gameObject.AddComponent<AudioSource>() as AudioSource;
    ambientAudioSource.loop = true;

Unity allows direct access to several GameObject properties from any of its components, thus ambientAudioSource.audio.loop is the same as gameObject.audio.loop or just audio.loop - that’s why you’re always modifying the same AudioSource (the first one).