- Home /
How do I get Button to play a random sound in Unity 5.0?
I attached DrumPad a C # script to my Drummer, an empty. I added a few sound samples to Drummer. I added a Drum1 button to my scene. When I play the scene the sound plays once, when I press the button I get the same sound instead a possible random sound. PLEASE HELP me with my script. I wrote the following code in Unity 5.o
using UnityEngine; using System.Collections;
[RequireComponent(typeof(AudioSource))] public class DrumPad : MonoBehaviour { public AudioClip [] clips;
// Use this for initialization
void Start () {
LetsPlay ();
}
void LetsPlay(){
int clipPick = Random.Range (0, clips.Length);
GetComponent<AudioSource>().clip = clips [clipPick];
GetComponent<AudioSource>().Play ();
}
}
Answer by alex_hajdu · Mar 13, 2015 at 10:57 AM
To make it simple, let's use GUI button.
Attach your script to some GameObject in the scene.
Make your LetsPlay method public so GUI button can handle it.
public void LetsPlay(){
int clipPick = Random.Range (0, clips.Length);
GetComponent<AudioSource>().clip = clips [clipPick];
GetComponent<AudioSource>().Play ();
}
Drag & Drop script component to gui button On Click () handlers and select LetsPlay method
Why didn't I think of making this method public! Thank you!
Answer by NerdRageStudios · Mar 13, 2015 at 09:20 AM
try simplifying this.
GetComponent<AudioClip>().PlayOneShot(clips[Random.RandomRange[0, clips.Length]);
Typing this without my editor, so check the syntax :)
Your answer
Follow this Question
Related Questions
Randomly play audio 0 Answers
Guys i need help with audio! 0 Answers
Choose from 2 audio Sources 2 Answers
Playing Sound 2 Answers
Playing audio immediately 1 Answer