My problem is that when i click on an object multiple times the sound just keeps repeating/echoing. How can i set the co-routine or function to wait until clip and animation is finished playing before allowing another mouse click?
Any help will be appreciated. Thank you!
Here is my snippet:
using UnityEngine;
using System.Collections;
public class A_LetterScript : MonoBehaviour {
private Animator animator;
private int State = 0;
private AudioSource audioSource;
public AudioClip aPageVoice;
void Start ()
{
animator = this.GetComponent<Animator>();
animator.SetInteger ("State", 0);
}
private void OnMouseDown()
{
Debug.Log("clicked.");
animator.SetInteger ("State", 1);
StartCoroutine ("Sound");
StartCoroutine ("Wait");
}
IEnumerator Wait ()
{
yield return new WaitForSeconds (5.0f);
animator.SetInteger ("State", 0);
}
IEnumerator Sound ()
{
//this is to sync my sound with my animation
yield return new WaitForSeconds(1.2f);
//this is to set my volume
audio.PlayOneShot(aPageVoice, 0.7F);
}
}
Hi. Try this. Declare a global variable: bool playing
, initialize it to false, and modify the event mousedown for calling a second yield
with the duration of the audio, after the second yield
, set the variable playing
to false
bool playing;
float audioLength;
OnMouseDown(){
if(!playing){
StartCoroutine ("Sound");
}
}
IEnumerator Sound ()
{
yield return new WaitForSeconds(1.2f);
audio.PlayOneShot(aPageVoice, 0.7F);
yield return new WaitForSeconds(audioLength);
}
Try this:
IEnumerator Sound ()
{
//this is to sync my sound with my animation
yield return new WaitForSeconds(1.2f);
//this is to set my volume
if(!audioSource.isPlaying)
audio.PlayOneShot(aPageVoice, 0.7F);
}
Hi this seems to work.
private Animator animator;
private int State = 0;
private AudioSource audioSource;
public AudioClip aPageVoice;
private bool canClick = true;
public bool playing;
public float audioLength;
void Start ()
{
animator = this.GetComponent<Animator>();
animator.SetInteger ("State", 0);
}
private void OnMouseDown()
{
Debug.Log("clicked.");
if (!playing && canClick) {
animator.SetInteger ("State", 1);
StartCoroutine ("Sound");
StartCoroutine ("Wait");
}
}
IEnumerator Wait ()
{
yield return new WaitForSeconds (5.0f);
animator.SetInteger ("State", 0);
}
IEnumerator Sound ()
{
yield return new WaitForSeconds(1.2f);
audio.PlayOneShot(aPageVoice, 0.7F);
StartCoroutine ("WaitSumMore");
}
IEnumerator WaitSumMore (){
canClick = false;
yield return new WaitForSeconds(audioLength);
canClick = true;
}