- Home /
Multiple audio sources; Unity won't let me attach in the inspector
I have two GUI buttons which I want to play a sound when that are clicked on. I have all my code in place and everything looks good, except for one problem: Unity won't allow me to attach the audio clips to the public variables in the inspector.
var hasBeenPressed1 : boolean = false;
var hasBeenPressed1 : boolean = false;
var audio1 : AudioSource;
var audio2 : AudioSource;
function OnGUI () {
GUI.Label (Rect (centering, 0, 130, 1350));
hasBeenPressed1 = true;
if (hasBeenPressed1 == true) {
audio1.Play();
}
}
GUI.Label (Rect (centering, 0, 130, 1350));
hasBeenPressed2 = true;
if (hasBeenPressed2 == true) {
audio2.Play();
}
}
}
I pared this down to just the audio. If it looks good and you try it, tell me if you were able to attach the clips to audio1 and audio2 in the inspector. Only other thing of note is I am on a Mac. Thank You
Answer by sethuraj · Jul 24, 2014 at 09:20 AM
You are doing it all wrong.You are trying to assign an AudioClip as AudioSource.First know the difference between AudioSource and AudioClip. AudioSource is like a player in which you can play many sounds.AudioClip is the sound file you are about to play on an audio source.
You cant drag an AudioClip like mp3,ogg,wav to an AudioSource element in your script through inspector.First you need to attach the AudioSource to the gameobject uisng the unity menu (Component>Audio>AudioSource) or via script.This will show you the proper way.Attach this script to any object and drag and drop your 2 audioclips to the audioclip section in inspector.
#pragma strict
var Clip_One:AudioClip;
var Clip_Two:AudioClip;
private var audio1 : AudioSource;
private var audio2 : AudioSource;
function Start()
{
audio1=gameObject.AddComponent(AudioSource);
audio2=gameObject.AddComponent(AudioSource);
}
function OnGUI ()
{
if (GUI.Button(Rect(10,70,120,30),"Play One"))
{
audio1.clip=Clip_One;
audio1.Play();
Debug.Log("Played One");
}
if (GUI.Button(Rect(10,120,120,30),"Play Two"))
{
audio2.clip=Clip_Two;
audio2.Play();
Debug.Log("Played Two");
}
}
Good Luck...!!!
Answer by darthtelle · Jul 24, 2014 at 07:52 AM
As an alternative solution to using multiple Audio Sources, you could have two public Audio clips in your script and one Audio Source attached to your object. Assign the audio clips in the editor, and then depending on which button you press, assign the clip to the audio source and play that.
if (hasBeenPressed1 == true)
{
audio_Source.clip = audio_Clip_1;
audio_Source.Play();
}
Your answer
Follow this Question
Related Questions
Audio not playing... 2 Answers
Audio.Play() not showing up 1 Answer
How do I play audio source on Maximize on Play / Audio Source wont play on Maximize 0 Answers
Play next song 1 Answer
Play Audio Sound OnTriggerEnter 2 Answers