- Home /
Play audio clip without a variable
Hey, Is there a way of calling a sound file straight from the code instead of setting a variable first (var theSound : AudioClip;)? I'm working on a game with people remotely so trying to make things easier to intergrate together. Thanks a lot.
Answer by aldonaletto · Sep 13, 2011 at 02:02 PM
You can load files using Resources.Load - but all files must be inside the Assets/Resources folder (or subfolders):
function PlayFile(file: String){ // file name without extension
var clip: AudioClip = Resources.Load(file);
// example 1: play with PlayOneShot
audio.PlayOneShot(clip);
// example 2: play without an AudioSource component
AudioSource.PlayClipAtPoint(clip, transform.position);
// example 3: play with Play
audio.clip = clip;
audio.Play();
}
...
PlayFile("Explosion"); // play sound file Explosion.wav or Explosion.mp3 etc.
...
Whoops, I forgot about this. Removed my answer and +1'd yours. :)
@mrsamdawes, If centralizing your AudioClip variables is something you feel would help your collaboration, consider using an Audio$$anonymous$$anager as a single point for creating most (if not all) of your SFX. There's a simple implementation of one here: http://www.blog.silentkraken.com/2010/04/06/audiomanager/, you could create public variables in this class, and have everyone reference this class for SFX.
Thanks, @zapdot - but you actually didn't need to remove your question - it has additional information, and maybe useful to the OP or to others as well.
Your answer