Hi
How would one instantiate an AudioSource , passing in the sound (WAV) file as a parameter using Unity’s java script. I have a lot of sound files in my game where I did not want to load all of those AudioSource objects into the scene, since most of them are one time sounds.
you would use the Resources folder and load them from there through the Resources class
Ok I was able to load it with :
_audio = Instantiate(Resources.Load(“AudioSourcePrefab”,GameObject).GetComponent(AudioSource));
However I was looking for a way of specifying the .wav file as a way to directly loading an audio instead of creating a prefab that includes the encapusulation of an audio source component.
I tried Instantiate(Resources.Load(“mywavfile”,AudioSource))
but it returned a null object.
You can change the specified audio clip for an individual audio source via script. Unless it’s something that’s necessary with your game’s design, you don’t need a separate audiosource for every wave file.
You can define an array of said clips to fill in the editor and reference them dynamically with an Enum or whatever you feel comfortable with.
If you are attempting to save memory by loading them on the fly, then the resources folder isn’t going to help you. You would need to use Asset Bundles for that.
1 Like
Thanks
So I am still stuck. How would you instantiate and access the array of audio clips ?
It’s generally just a matter of initialising the array and directly assigning the elements:-
var clips: AudioClip[];
function Start() {
clips = new AudioClip[numClips];
clips[0] = Resources.Load(...); // First clip
clips[1] = Resources.Load(...); // Second clip
...etc...
}
You can then access the elements by their index number. It might be more useful to use several separate variable names rather than an array, depending on what you are doing.
mlewis has this worked for you? I have been getting stuck on this and given up so far:
var asource : AudioSource = new AudioSource();
asource.clip = Resources.Load("mysound"); //null reference still
This only returns a null reference as well. I havent tried the prefab way yet… will tomorrow. Hope that will work! 
Prefab instantiating is working without any problems. Can someone explain to me why the other way won’t work? Thanks in advance!
AudioSource is actually a component, so the instance is both created and added to a target object using AddComponent. Instantiating a component with “new” won’t make it active in the game.
it doesnt mater if the code is correct, if the file isnt set as “streaming” it will return null.