Dim
Dim

Reputation: 4807

Reverse animation in unity 3D

I have an FBX object with animation. The object is a box with animation for opening. What I'm trying to do is when the user clicks a button the box will open (play open animation) and when the button is clicked again the box will close (play open animation backwards).

While the opening animation is playing and I click the button again the opening animation stops and the box starts to close, that works fine. The problem is that when the animation is finished (open) and then I click the button to close, the animation is not playing and it just jumps to a closed box without animation.

Here is my code:

public class ClickBtn : MonoBehaviour {

    public GameObject box = null;
    bool reverse = false;

    private void OnMouseDown()
    {
        Debug.Log(reverse);

        if (!reverse)
        {
            box.animation["Take 001"].speed = 1;
        }
        else
        {
            box.animation["Take 001"].speed = -1;
        }

        reverse = !reverse;

        box.animation.Play("Take 001");
    }
}

Upvotes: 2

Views: 5502

Answers (2)

Samhay
Samhay

Reputation: 248

When animation is finished its time is reseted to beginning.

Simple workaround set time to end before playing backwards.

public GameObject box;

bool direction = false;

private void OnMouseDown()
{
    Debug.Log(direction);

    if (!direction)
    {
        box.animation["Take 001"].speed = 1;


    }
    else
    {
        box.animation["Take 001"].speed = -1;

        //if animation already finisihed, set time to end before playing it backwards
        if(!box.animation.isPlaying){ 
            box.animation["Take 001"].time =box.animation["Take 001"].clip.length;

        }
    }

    direction = !direction;

    box.animation.Play("Take 001");
}

Upvotes: 2

Rwmxx
Rwmxx

Reputation: 166

your animation.WrapMode is set wrong (probably WrapMode.Once, which is default). In your case you could use:

WrapMode.PingPong: Ping Pong's back and forth between beginning and end.

animation.wrapMode = WrapMode.PingPong;

Mind you, you don't need

box.animation["Take 001"].speed = -1;

anymore, this is done automatically.

Upvotes: 4

Related Questions