Nullititiousness
Nullititiousness

Reputation: 371

how can I stop coroutine in Unity

I am using the Coroutine below to move several objects in a list in my game:

IEnumerator moveObjToRight  (Transform fromPosition, Vector3 toPosition, float duration, int newIndex)  {


        while (freePositions.Contains(objPositions[newIndex])) {

        freePositions.Add (objPositions [newIndex - 1]);
        filledPositions.Remove (objPositions [newIndex - 1]);

        float counter = 0;

    Transform startTrans = fromPosition;

    freePositions.Remove (objPositions [newIndex]);
    filledPositions.Add (objPositions [newIndex]);

        while (counter < duration) {                
            counter += Time.deltaTime;
            fromPosition.position = Vector3.Lerp (startTrans.position, toPosition, counter / duration);
            yield return null;

        }


        if (newIndex < objPositions.Count) {

            newIndex++;

            if ((newIndex == 9) || !freePositions.Contains (objPositions [newIndex]))   {

            isMovingLeft = true;

            yield return new WaitForSeconds (2.0f);

            if (freePositions.Contains (objPositions [newIndex - 2])) {

            toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );
            yield return StartCoroutine(moveObjToLeft(startTrans, toPosition, 1.0f, newIndex - 2));

I use it call it in the following way:

StartCoroutine(moveObjToRight(objs [objs.Count - 1].getObjGameObject().transform, new Vector3(objPositions[indexInObjPositions + 1], objPositionY, camera.nearClipPlane), 1.0f, indexInObjPositions + 1));

I have been getting the following error:

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.get_position ()

in my game, pointing to the line within the coroutine:

toPosition = new Vector3(objPositions[newIndex - 2], startTrans.position.y, startTrans.position.z );

I believe it's because I am not stopping the coroutines when I destroy the game objects. How can I stop the coroutine above?

Upvotes: 0

Views: 945

Answers (1)

Jo&#227;o Martins
Jo&#227;o Martins

Reputation: 332

You can either use the command:

 StopCoroutine(moveObjToRight);

Before destroying the object, or you can use a boolean as flag to know when the object is alive or destroyed and to control if the coroutine runs or not.

bool alive = true;

Ienumerator moveobj{
    if(alive){
    //run code
    }
}

Destroy(object);
alive = false;

Upvotes: 1

Related Questions