- Home /
Only able to play a single sound through AudioSource.
I am trying to set up my script so that it will choose randomly from three sounds when I fire the weapon. It works if I set it up with one sound but fails to play anything when I put in my if statement to attempt to randomise the sound. I've been poring over the manual entries on AudioSource and AudioClip all morning and have not been able to figure this out.
public AudioClip launchMissile1;//audio for firing missile
public AudioClip launchMissile2;//audio for firing missile
public AudioClip launchMissile3;//audio for firing missile
//capture keyboard input to launch a starbase missile
if(Input.GetKeyDown(keyFire))
{
if(weaponLoaded)
{
FireWeapon();
float randSound = Random.value;
if(randSound < 0.33)
{
print ("sound1");
audio.clip = launchMissile1;
audio.Play();
}
if(randSound >= 0.33 && randSound <= 0.66)
{
print ("sound2");
audio.clip = launchMissile2;
audio.Play();
}
if(randSound > 0.66)
{
print ("sound3");
audio.clip = launchMissile3;
audio.Play();
}
rigidbody.AddRelativeForce(Vector3.up * recoil);
}
else
print ("We're still loading the launcher!"); //debugging info
}
So the question at it's most basic is "How do I change the clip that my audiosource is playing?".
Thanks in advance for any assistance.
Is it printing the debugs? If not, trying using Debug.Log ins$$anonymous$$d of print, i once had print not work. Or was blind. :)
I'm pretty sure I've done this exact thing in one of my projects...
Ah my apologies, I did mean to mention that! Yes it is printing the debug text. Sound1, sound2, sound3 etc.
Answer by Khada · Apr 17, 2013 at 08:04 AM
This works for me (object must have attached AudioSource):
public AudioClip clip1; //assigned via inspector
public AudioClip clip2; //assigned via inspector
public AudioClip clip3; //assigned via inspector
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
int rand = Random.Range(0,3);
switch(rand)
{
case 0: audio.clip = clip1; break;
case 1: audio.clip = clip2; break;
case 2: audio.clip = clip3; break;
}
if(audio.clip != null)
audio.Play();
}
}