I cant get it to work. I want to load three audio files at the beginning of a script and play them later responding to mouse clicks or touches. But I don’t get it to work!
I fiddled around with AudioSource and AudioClip but nothing actually works. It seems that I always have to connect the audio source to a Object.
testcode:
//Audios
var aReleaseCube:AudioClip;
var aLiftCube:AudioClip;
var aCubeOnSlot:AudioClip;
function StartMainScript()
{
aLiftCube = Resources.Load("sounds/cube_up",AudioClip);
aReleaseCube = Resources.Load("sounds/release_cube",AudioClip);
aCubeOnSlot = Resources.Load("sounds/cube_on_slot",AudioClip);
aCubeOnSlot.Play();
//define some Levels
LoadLevel(currentLevel);
}
There is no Play() function on audio clips; only on AudioSource. You might think “I don’t want all that crap!”, but Unity forces you to use an AudioSource anyway. I use a source created as a component on my Player GameObject.
Note that I’m using slightly different code to load each of the three clips. All of those formats will work; they all do the same thing. You can use whichever one you like best. There’s JS equivalents for each of these methods.
Next, you need an AudioSource. I normally attach this to a GameObject somewhere, using the editor. You don’t need three audio sources. And, for correct 3D positioning (whether you just want left/right balance or more sophisticated 3D positioning), it’s easier to just set up one AudioSource and set its properties in the editor. Yes, you could instantiate it using a script as well. Your choice.
Finally, to play the sounds, use the PlayOneShot function.
audioSource.PlayOneShot(clip1);
This way, you can play a wide array of clips through one audio source.
If I understand correctly, you want to be able to play any of these audio clips at the same time. For that you’ll need 3 separate audio sources. Write a script that does this:
audio.clip = aCubeOnSlot;
audio.Play();
and attach it to 3 separate game objects with audio sources. Then put it inside of a public function that you can call from another script.