yield and StartCoroutine

Hello,

I got a problem with the yield and StartCoroutine command using c#.

I have translated the Server Side Highscore Script from the Wiki into c#.

It runs fine if i call the function with StartCoroutine from the start function. But if i try it from another function it looks like it isn´t executed properly. i get no Debug.Log() or any other message from the functions.

For the getScores function this will work fine but i also have a postScore(string name, int score) function that is called during the game

Here is some of the code

private void Update()
{
    if(!m_bScoreLoaded)
    {
        m_bScoreLoaded = true;
        LoadScores();
    }

}

private IEnumerator LoadScores()
{

    yield return StartCoroutine(getScores());
    // assignment of the results comes here
}

I Hope someone can explain what i am missing or doing wrong.

You can’t call StartCoroutine from an Update function. I believe what you’re doing there is the right way to go about it, although there may be a better way. I only started on coroutines this week, so I’m pretty new to them as well.

Your LoadScores function is a coroutine itself, so it needs to be called using StartCoroutine, like getScores() is called. If you call a coroutine without using StartCoroutine(), it will simply not execute at all.

Starting coroutines from Update() is perfectly fine.

what exactly does not work and how does the corresponding code look?

I solved the problem by calling the function from the start-function. But I am still interessted in an explanaition.

Here is the code that works:

IEnumerator Start () 
{
    yield return StartCoroutine(getScore());
}

And here is the code that don´t work

private void Update()
{
    if(!m_bScoreLoaded)
    {
        m_bScoreLoaded = true;
        LoadScores();
    }

}

private IEnumerator LoadScores()
{

    yield return StartCoroutine(getScores());
    // assignment of the results comes here
}

but as i understand tomvds i have to write

private void Update()
{
    if(!m_bScoreLoaded)
    {
        m_bScoreLoaded = true;
        StartCoroutine(LoadScores());
    }

}

Will try it today thx

You don’t need IEnumerator Start, or a yield return in start.

Just do

void Start()
{
    StartCoroutine( GetScore() );
}

However, your second method of using Update and a Coroutine will work too.[/code]

As I understand it, he wants to wait for GetScore to complete and then take some action. In that case, the function calling GetScore needs to be a Coroutine (and therefore an IEnumerator) as well, or it won’t be able to use yield to wait for completion.

I completely understand the need for a coroutine. What I’m saying is that the Start method should not be IEnumerator. Let Start call the Coroutine.