adding audio source through code

how would i go about doing this, i have got loads of prefabs but they all have the same script attached, so this would save a lot of time.


Hey Undead!

That’s a good question, as when one adds more than one audioSource to the same GO in the editor, things get confusing… Better to do it in code!

var mySources : AudioSource[];
var nbOfSources : int;

function Start()
    mySources = new AudioSource[nbOfSources];

    for(source in mySources)
        source = gameObject.AddComponent("AudioSource") as AudioSource;


Then, you can do

mySources[x].clip = myClip;

or whatever you need!

But stop using audio.whatever, as it will refer to the first added source only, if I’m not mistaken…