Skip to main content
5 of 5
deleted 2 characters in body

How do I use coroutines to animate properly?

I have a coroutine, which I called from the Update() method on every click.

First, I call AddTrunk() to add to my trunkList, then I use my coroutine to move the animation for 0.3 seconds. After 0.3 seconds, it calls Destroy(), and then it changes transform.position. However, before completing the animation, it runs transform.position; it first my tree down first, and then does the animation.


This is where I call my coroutine:

void Update () 
{
    if (Input.GetMouseButtonDown (0)) 
    {
        AddTrunk ();

        if (!isRunning) 
        {
            StartCoroutine (BranchOutAnimation ());
        }
    }
}

Here is the coroutine BranchOutAnimation():

IEnumerator BranchOutAnimation()
{
    while (true) 
    {
        isRunning = true;
        iTween.MoveTo (trunkList[index], 
            new Vector3 (trunkList[index].transform.position.x 
            - 5f, trunkList[index].transform.position.y, 
            trunkList [index].transform.position.z), 0.3f);
        yield return new WaitForSeconds (0.3f);

        Destroy (trunkList [index]);
        trunkList.RemoveAt (index);
        transform.position = new Vector3 (transform.position.x, transform.position.y 
            - treeHeight, transform.position.z);
        isRunning = false;
        yield break;
    }
}

What am I doing wrong?