Hi everyone, i’m trying to create a script where if you touch a gui.Button, an audioclip plays randomly, for instance, if you touch the button, the audioclip plays four times, if you touch it again, the audioclip plays twice and so on. can you help me, please?
this is what i have, but it doesn’t work
.
private int rdn;
public bool showButton=true;
void OnGUI(){
if (showButton) {
if (GUI.Button (new Rect (Screen.width / 2, Screen.height / 2, 60, 60), “PLAY”)) {
rdn = Random.Range (1, 5);
for (int i=0; i<rdn; i++) {
audio.Play();
Debug.Log("repeate: "+rdn);
}
}
}
}
Its very easy to do.Just play the clip.wait till it finishes and repeat the procedure again until it reaches the repeat count.You can use a coroutine for this.Here is an example
//The Audioclip which we are playing
public AudioClip Clip;
//The AudioSource to which we are playing
private AudioSource Source;
void Start()
{
//Add the audiosource
Source=gameObject.AddComponent<AudioSource> ();
}
void OnGUI()
{
//If the button is pressed
if(GUI.Button(new Rect(10,10,70,30),"Play"))
{
//Stop currently playing audio
Source.Stop();
//You can also stop the courutine here
//Start th coroutine with a random repeat range
StartCoroutine("PlaySoundClip",Random.Range(1,5));
}
}
//The coroutine in which we play our audio clip
IEnumerator PlaySoundClip(int RepeatCount)
{
//Log out how many times we are going to play the clip
Debug.Log (RepeatCount);
//Loop until the repeat count
for(int i=0;i<RepeatCount;i++)
{
//Play the audioclip as oneshot
Source.PlayOneShot(Clip);
//Wait until the clip has been finished playing
yield return new WaitForSeconds(Clip.length);
}
}
Hop this helps…