- Home /
Please help with playing music for button click
In canvas, I have attached few buttons. Each button has button script. I have imported some audio and there is a game object audio in that scene which has audio script.
Now, I press a button, how can i play the audio? If i copy those scripts as a single one, i can make it play.
But how do i keep them separately and make them to play?
Answer by Harardin · Aug 13, 2015 at 07:34 PM
You need to create a script
public class YourName : MonoBehaviour {
private AudioSource source;
public AudioClip clip;
// Use this for initialization
void Start () {
source = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Your button")) // Button can be setup in Edit->ProjectSettings->Input
{
source.PlayOneShot(clip);
}
}
}
And don’t forget to add Audio Source in Add Component in Inspector
And my advise look this tutorial : http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/sound-effects-scripting?playlist=17096
TO play music from one script in another you need to create seperet public void Playmusic() and get it from another script with
GetComponent<musicScript>().Playmusic().
Answer by voporak5 · Aug 13, 2015 at 06:53 PM
download SoundManagerPro3 from asset store. it's really easy to use and watch his tutorials.