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 on a single object which belongs to a list, bearing in mind that it has parameters and several objects within a list may be using this coroutine?

There’s the StopCoroutine method, but in your case, it’s probably easier to have the coroutine end itself when the transform is null, e.g:

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

Make sure nothing is null before starting the coroutine, and check if your transform becomes null during the coroutine each frame as shaderop suggests.

Except you can’t return a value from an iterator, you would use yield break.