- Home /
Help with IEnumerator and if sound is playing
I have some problems with my code. First off there is something wrong with my audio.isPlaying-code. It doesnt detect that a sound is already playing. Whats wrong?
And my second problem is that I can get the IEnumerator-code to work. I get a "unexpected symbol"-error. Please help a newbie out... The code is:
public class ToScene2 : MonoBehaviour {
public AudioClip ljud2;
private AudioSource audio;
// Use this for initialization
void Start () {
audio = Camera.main.GetComponent<AudioSource> ();
}
public void OnClick(){
// If audio isn't already playing, play it.
if (!audio.isPlaying) {
audio.PlayOneShot (ljud2);
}
else {
Debug.Log ("A sound is already playing");
}
IEnumerator waitThreeSeconds()
{
yield return new WaitForSeconds(3.0f);
//Go to next scene
Application.LoadLevel ("scen-rosa");
}
StartCoroutine(waitThreeSeconds());
}
}
Answer by sleepandpancakes · May 07, 2017 at 07:40 PM
Place the IEnumerator code outside of the OnClick() function. You can't declare a method inside of another method.
Answer by FM-Productions · May 05, 2017 at 01:06 PM
Hi,
instead of going with audio.PlayOneShot (ljud2);
, set the right clip of the audiosource in the Start() function -> audio.clip = ljud2;
PlayOneShot is only necessary if you want to play multiple clips on the same audio source.
Then, in onClick, in think this should work.
if (!audio.isPlaying) {
audio.Play();
}
Good to hear @klasklasklas :) Also, I (and I think everyone else too) would also appreciate an upvote for the answer if it worked.
Sorry, @eicher. I'm a newbie! Done it now. Thanks again.
I upvoted your answer, however i don't really see how the answer is actually related to the question."PlayOneShot" does work as well. The actual error is that he declared his coroutine inside another method. So replacing PlayOneShot(ljud2) with clip = ljud2 doesn't solve the problem.
Your answer
Follow this Question
Related Questions
Movement speed based on audio input 1 Answer
Audio Clip Playing every frame 2 Answers
Do unused audio sources hurt performance? 0 Answers
OnTriggerExit stop audio 1 Answer