StopCoroutine not working not even StartCoroutine(string), StopCoroutine(string) in unity3d

StackOverflow https://stackoverflow.com/questions/19947808

  •  30-07-2022
  •  | 
  •  

Domanda

I can't understand why.

I already read lots of documents about it and there are lots of comments that

StopCoroutine(string) can only stop the coroutine starts with StartCoroutine(string)

the code is below.

In Class CharTouchControl.cpp

if( Input.GetKeyDown( KeyCode.Q ) )
{
    _CharControl.StartCoroutine("useFever", 10);
}

_CharControl is a member of CharTouchControl and of course _CharControl is referencing the CharControl instance below.

And InClass CharControl

public IEnumerator useFever(float _duration = 10)
{
    if( m_nUseFever < _nFeverMax )
    {
        Debug.Log("Stop!!");
        StopCoroutine("useFever");
        yield return new WaitForEndOfFrame();
    }

    m_fgCharState = CharState._FEVER;

    // fever particle
    m_psFeverPaticle.Simulate(4);

    yield return new WaitForEndOfFrame();
} // end of useFever

When m_nUseFever < _nFeverMax is true, i can see "Stop!!" log,

but the coroutine don't stop and simulate paticles.

anybody help for this?

È stato utile?

Soluzione

Just as Jerdak mentioned, you should use yield break when your inside the Coroutine. the coroutine will automatically stop when it finishes its code block. Using yield break, should send it to the end of the code block.

Additionally you could modify your code so that it only runs the code block if the condition is true. Ive done this in the example below. If the condition is false the coroutine will just wait for the end of the frame and then exit.

public IEnumerator useFever()
{
    if( m_nUseFever > _nFeverMax )
    {
        m_fgCharState = CharState._FEVER;

        // fever particle
        m_psFeverPaticle.Simulate(4);
    }

    yield return new WaitForEndOfFrame();        
} //Coroutine automatically exits here

EDIT: Dan Puzey brought up a good point, Are you sure shouldn't be using

Invoke("useFever",10) or InvokeRepeating ("useFever",10,1)

instead? From your code it looks like you just want to run the useFever function in 10 seconds. If thats the case, you should be invoking it instead of running it as a coroutine, and useFever should be a normal function.

Just for reference, there is also CancelInvoke("useFever")

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top