Assign audio clip via scripting to an object

Hello,

I was searching the forums for an answer, but couldn’t find anything so far. What I am trying to do is to assign an audio clip to an object during runtime.
I couldn’t find anything which would say how can this be done.
Here’s my script so far:

var object1 : GameObject;
var sound_name : AudioClip;

function Start(){
	
	object1 = gameObject.Find("object1");
	object1.AddComponent(AudioSource);
	audio.clip = Resources.Load(sound_name);
	
}

Unfortunately this only adds the audio source component to the object but the audio clip will be null.
Any ideas?

Thanks in advance.

Untested, but should do the trick:

function Start(){
	
	object1 = gameObject.Find("object1");
	audioSource = object1.AddComponent(AudioSource);
	audioSource.clip = Resources.Load(sound_name);
}

If this still does not work, the resource cannot be loaded (for whatever reason).

Thanks really much, this worked pretty well :slight_smile: