How do I use coroutines to animate properly?

by Kartik Shah   Last Updated April 27, 2017 06:13 AM

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?



Related Questions


Fade out / fade in scene w/ loading screen

Updated April 29, 2016 08:05 AM

Parameter 'Blend' doesnt exist

Updated February 16, 2018 23:13 PM

Problems exporting animation to Unity 5

Updated July 19, 2017 22:13 PM


Play/Stop All Animations in a Project

Updated October 23, 2016 09:05 AM