Unity3D – Add Multiple Audio Sources – Javascript

Add Audio Sources to THIS GameObject – Advanced

1. Create a Empty Game Object and assign AddAudioSources.js:


#pragma strict

var myAudioClip : AudioClip[]; // Array of audio clips - fill it in Inspector
var mySources : AudioSource[]; // Array of audio souces
var nbOfSources : int; // Assign in Inspector the number of souces into array 
 
function Start()
{ 
    mySources = new AudioSource[nbOfSources]; // Create an Array of Audio Source
 
    for(source in mySources)// genera un array del tipo -> mySources[0].clip...
    {
        source = gameObject.AddComponent("AudioSource") as AudioSource;
    }
    
    // If you have 3 intems into array...
    mySources[0].clip = myAudioClip[0];
    mySources[1].clip = myAudioClip[1];
    mySources[2].clip = myAudioClip[2];
    
    // Others setup...
    mySources[0].playOnAwake = false; // not play in awake
    mySources[0].volume = 0.2; // setup volume
    mySources[0].Play(); // play the audio clip
 
}
	
function Update(){
	}

2. Inspector> AddAudioSources.js> AudioClip[]>Size, resize the array and DRAG AND DROP your .wav files into empty slots

3. Inspector> AddAudioSources.js> AudioSource[]>Size, resize the array

4. Play and watch inside Inspector> Empty Game Object

Add Audio Sources to ANOTHER GameObject

1. Create a Cube

2. Create a Empty Game Object and assign AddAudioSources.js:


#pragma strict

var myAudioClip : AudioClip[]; // Array of audio clips - fill it in Inspector
var mySources : AudioSource[]; // Array of audio souces
var nbOfSources : int; // Assign in Inspector the number of souces into array 
 
private var cubeobj : GameObject; // for find with name gameobject 
 
function Start()
{ 
    cubeobj = GameObject.Find("/Cube"); // Find gameobject with name

    mySources = new AudioSource[nbOfSources]; // Create an Array of Audio Source
 
    for(source in mySources)// genera un array del tipo -> mySources[0].clip...
    {
        source = cubeobj.AddComponent("AudioSource") as AudioSource;
    } 
}
	
function Update(){
	}

2. Inspector> AddAudioSources.js> AudioClip[]>Size, resize the array and DRAG AND DROP your .wav files into empty slots

3. Inspector> AddAudioSources.js> AudioSource[]>Size, resize the array

4. Play and watch inside Inspector> Cube