Corutine not behaving like it should?

Hello there…

Alright, so im new to the whole yield keyword and corutines in unity.
So im pretty confused as it is, and not having it behave like it ‘should’, doesnt make it easier :stuck_out_tongue:

Anyway, here’s what i want to do:

This is taken directly from here.


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    IEnumerator Do() {
        print("Do now");
        yield return new WaitForSeconds(2);
        print("Do 2 seconds later");
    }
    void Example() {
        Do();
        print("This is printed immediately");
    }
}

And this is my code:


private void SetView()
{
    ActivateFirstPersonView();
    Debug.Log("This is immediately after");
}

public IEnumerator ActivateFirstPersonView()
{
    Debug.Log("Starting");
    yield return new WaitForSeconds(2);
    Debug.Log("Finished");
}

The problem is, ‘ActivateFirstPersonView’ isnt being called at all.

If i use,

StartCoroutine(ActivateFirstPersonView());

instead. Then it behaves like it should, I just dont get it?

Is it a documentation error? I hope not, because i would like to call the method without starting a coroutine, for simplicity’s sake.

"i would like to call the method without starting a coroutine, for simplicity's sake." That doesn't make any sense. Please elaborate

If you create a blank project, does the sample code not work?

The documentation is bugged; try it. That's what happens when the script reference is only auto-converting the original UnityScript. It explicitly states here that you need to use StartCoroutine (unless you plan to move through it manually, but that won't run as efficiently, and will require more code than the function call). http://answers.unity3d.com/questions/14495/confused-about-coroutines.html

Yeah, you need to use StartCoroutine to start coroutines in C#. That looks like a docs bug.

If you want to avoid manually using StartCoroutine, then you have to use Unityscript and not C#.

1 Answer

1

Thanks for your comments guys.

This is what i might end up with:


Class 1:

private void SetView()
{
    StartFirstPersonView();
    Debug.Log("This is immediately after");
}

Class 2:

public void StartFirstPersonView()
{
    StartCoroutine(ActivateFirstPersonView());
}

private IEnumerator ActivateFirstPersonView()
{
    Debug.Log("Starting");
    yield return new WaitForSeconds(2);
    Debug.Log("Finished");
}

It might be a bit exessive, but i want to keep all the coroutine responsibility inside class 2.

If you guys have a more clever way of doing this, let me know.

It's fine this way. Also keep in mind that coroutines always run on a MonoBehaviour instance, so it's always better to use Startcoroutine of the script to which the coroutine belongs to. If the script instance gets destroyed all coroutines that run on this script are terminated immediately.