1
\$\begingroup\$

Good evening all, about to pull my hair out because I cant figure out why I keep getting this error. The problem is this, I need the player to click on the start button, then, the screen will fade to black and load level 1. (logic and code was provided by a Brackeys tutorial(https://www.youtube.com/watch?v=0HwZQt94uHQ), awesome guy)

here is the code for the button.

public void OnPointerClick(PointerEventData eventData)
{
    float fadetime = GameObject.Find("_GM").GetComponent<FadeScreen>().BeginFade(1);
    yield return new WaitForSeconds(fadetime);
    SceneManager.LoadScene("Level_01");
}

Now the error is highlighted with a red line under OnPointerClick just after "public void".

And the error is - The body of 'StartGame.OnPointerClick(PointerEventData)' cannot be an iterator block because 'void' is not an iterator interface type. Ive been googling for around four hours now and I'm coming up blank.(lack of sleep might be causing me to miss something)

Please can someone point out what I cannot see myself? Also I do apologize if this has been asked before, I was not able to find anything on the subject. Thank you kindly.

\$\endgroup\$
2
\$\begingroup\$

The yield return new WaitForSeconds(time) construct only works in Coroutines.

A coroutine must be started with the StartCoroutine(name) method and must itself be a method which returns an IEnumerator.

So first you need to write your coroutine as a new method:

IEnumerator FadeToNextLevel() {
    float fadetime = GameObject.Find("_GM").GetComponent<FadeScreen>().BeginFade(1);
    yield return new WaitForSeconds(fadetime);
    SceneManager.LoadScene("Level_01");
}

And then you need to launch that coroutine from the method which is your button handler:

public void OnPointerClick(PointerEventData eventData) {
    StartCoroutine("FadeToNextLevel");
}
\$\endgroup\$
  • 1
    \$\begingroup\$ "A coroutine must be started with the StartCoroutine(name) method" - there are two small caveats to this. One: you can do this without reflection looking up the name at runtime by using StartCoroutine(OnPointerClick()); (ie. passing the IEnumerator the method returns, rather than a delegate or name of the method). The second is that many of the messages MonoBehaviours can receive can be used directly as coroutines; eg. IEnumerator Start() or IEnumerator OnMouseDown() - Personally I prefer the style of explicitly calling StartCoroutine() but I thought I should point out the alternative. \$\endgroup\$ – DMGregory Apr 26 '16 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.