Playing animation backwards

I have an animation, I want to press a gui button image called “closed” and the animation will play forwards and the gui button will change to the other image called “open” then when i press the “open” button the animation will play backwards and the image change back to “closed”, I am a modeller not a coder but I am trying to learn, I tried this code and the animation plays forward but the image state doesn’t change I am unsure how to make the animation play backwards and make the image state change.

This is the code I have been trying, any help would be much appreciated, I have commented out code I have tried but didn’t work.

else if (GUI.Button(BellowsPosition, bellows ? bellowsClose : bellowsOpen, new GUIStyle()))

	{
		bellows = !bellows;
		//bellows = true;//toggleRender();
		
		bellowsAreOpen = bellows = true;
		//print ("open the bellows");
	} 
	else
	{
		//bellows = false;
		bellowsAreOpen = bellows = false;
		//print ("close the bellows");
	}
	
	//print("bellows: " + bellows);
	
	if (bellows)
	{
		//other.animation.Play();
		float speed;
		GameObject BellowsL = GameObject.Find(BellowL);
	    BellowsL.animation.Play();
		
		GameObject BellowsR = GameObject.Find(BellowR);
		BellowsR.animation.Play();

1 Answer

1

Not sure about your whole set-up, but this sort of thing can work:

Say the animation is named “open.” After closing or opening it needs to stay in that position. Sometimes it will just do that, but to be sure, set to clampForever (Inspector.) “Open” will play from 0 to 1, where it is fully open. If will technically keep playing to 2,3,4, but the clampForever says those count as time=1, fully open.

When you want to close, set speed to -1 to go backwards. The “open” animation is probably at about 15 by now. You don’t want to wait 14 seconds while it goes to 14, 13 … , so reset time to 1:

if(bellowsOpen==false) {
  bellows.animation["open"].normalizedTime=0; // start (closed)
  bellows.animation["time"].speed=1; // forwards
  bellows.animation.Play("open");
}
else {
  bellows.animation["open"].normalizedTime=1; // end (open)
  bellows.animation["time"].speed=-1; // backwards
  bellows.animation.Play("open");
}

That giant if/else should be running only when you click the button. Otherwise it will constantly reset to the 1st/last frame (setting normalizedTime zips the animation to that point.) I'd also test it for just bellowsL, in case there's so odd interference. No need to set to ClampForever each time (and it would normally be set specifically for Take001. Easier to set ClampForever in the Inspector.

That little area bellows=!bellows; happens only when someone clicks the button. All of the code that plays the animations should also be there, so it runs only when they click the button. Seems odd to run only once, since you need to animate each frame. But that code isn't playing the animation -- it's telling Unity to play it (either backwards form the last frame, or forwards from the 1st.)