- Home /
Add audio clip to a specific audio source
I'm trying to add different audio clips to different audio sources. Right now I can get both audio clips in, but they overwrite each other in the first audio source and the second audio source is never used. The second audio source is on a different game object.
//controls if the sound is on or off bool Sound1On = false; AudioClip Sound1;
bool Sound2On = false; AudioClip Sound2;
void Start () {
//load the object to attach sound to
GameObject Object1 = GameObject.Find("Object1");
GameObject Object2 = GameObject.Find("Object2");
//attatch a audio component to the GameObject
Object1.gameObject.AddComponent<AudioSource>();
//load in the SFX, add SFX settings
Sound1 = Resources.Load("Audio/SFX-Sound1") as AudioClip;
Object2.gameObject.AddComponent<AudioSource>();
Sound2 = Resources.Load("Audio/SFX-Sound2") as AudioClip;
}
The next code is called from a separate class that controls the movement: when you press down sound1 plays and when you press up, sound2 plays. However, they both play in the same audio source.
//SOUND 1 public void RunSound1(bool bMoving){
//play the SFX if character is moving and sound isn't already playing
if ((bSound1On == false) && (bMoving == true)){
audio.clip = Sound1;
audio.loop = true;
audio.playOnAwake = false;
audio.Play();
//sets the SFX to playing
bSound1On = true;
}
//turns off SFX if character is not moving
if (bMoving == false){
audio.clip = Sound1;
audio.Stop();
//sets the SFX to not playing
bSound1On = false;
}
The code for sound 2 is the exact same.
//SOUND 2 public void RunSound2(bool bMoving){
//play the SFX if character is moving and sound isn't already playing
if ((bSound2On == false) && (bMoving == true)){
audio.clip = Sound2;
audio.loop = true;
audio.playOnAwake = false;
audio.Play();
//sets the SFX to playing
bSound2On = true;
}
//turns off SFX if character is not moving
if (bMoving == false){
audio.clip = Sound2;
audio.Stop();
//sets the SFX to not playing
Sound2On = false;
}
}
So basically, I want Sound2 to load into Object2's audio source. Thanks for any help.
Answer by Tetrad · Jul 09, 2010 at 08:24 PM
audio
probably only returns the first audio instance on an object. Either hook up your audio sources as a prefab and hook up public member variables for audio sources to know which one is which, or use an empty gameobject child that has its own audio source.
Thanks for the reply, I'm using 2 different game objects, each has an audio source. I'm trying to add the audio clip to the second game object. But, I don't know how to specify the second object rather than the first.
In your case, just do Object1.audio/Object2.audio, probably.
Your answer
Follow this Question
Related Questions
Play sound from an array, not random, and only once 3 Answers
When is audio file loaded to memory 0 Answers
Intensity of sound. -1 Answers
Using Distance from AudioSource 0 Answers
Set audio clip to 3D in script 1 Answer