Am I understanding sound correctly?
I have a bunch of .wav files in my projects folder. I want a random sound to play when I click a button. One sound is “Up1”
I tried:
audio.PlayOneShot(“Up1”);
and
audio.clip = “Up1”;
audio.Play();
But it doesn’t accept string references to the sound.
I’ve read about the game objects and audio sources, but do I really need to attach a sound to a game object to play it? Do I need a source for each possible sound? I have many. Is this really how it works? If not, how can I reference a sound sitting in my project folder so I can play it?
Thanks guys.
Hello,
The audio property of a GameObject references an AudioSource ( Unity - Scripting API: AudioSource) which has the Play/Stop controls.
The AudioSource doesn’t know the file, though, that’s the job of the AudioClip ( Unity - Scripting API: AudioClip ). AudioClips are how audo files are stored/loaded by the engine.
You can either set the audio clip in the source via the Unity editor or if you want to do it run time, you can use the function Resources.Load() function ( Unity - Scripting API: Resources.Load ) so long as the files are under Resources folder.
So your script may look like this:
audio.PlayOneShot(Resources.Load('Up1'));
or:
audio.clip = Resources.Load('Up1');
audio.Play();
Thanks Timmer,
I saw all those links you mentioned, but still not sure I understand.
I tried using the code directly, and it either crashed my browser or did nothing.
Then I made a game object and attached one sound file to it. I referenced the game object in variable : pSnd
I can get the attached sound to play with this:
pSnd.audio.Play()
;
But when I try to change the sound with:
audio.clip = Resources.Load("Down1");
Browser crashes.
if I try:
pSnd.audio.clip = Resources.Load("Down1");
pSnd.audio.Play();
It doesn’t crash, but nothing happens.
So, do I have to make a game object for each sound, or can I cause one game object to switch sounds? Really, I’d like to just play the sound without a game object but still not sure if you’re saying that’s possible or not.
Ok, now that I researched “Resources.Load” I see that my assets need to be in Resource folder, I thought it could reference anything in my project window.
Thanks! it works!!