Animation on Button press, then same button plays in reverse

Hello all

I have a simple object cube, when i press KeyR it plays an animation of the cube changing scale (getting bigger), Happy days.

However when i press KeyR again, i want it the play the animation again but in reverse.

so i can grow the cube and shrink the cube just by pressing R

I have a very simple script attached that is assigned to my cube, which gives me a menu in inspector to select the Key and which transition condtion to trigger play, as per below

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RiskAnimation : MonoBehaviour
{
    public KeyCode MyKey;
    public string RiskTrigger;

    void Update()
    {
        if (Input.GetKey(MyKey))
        {
            GetComponent<Animator>().SetTrigger(RiskTrigger);
        }
    }
}

My animator parameters look like this, i have an Idle state with no animation attached, with a transition to my animation with a trigger

I either want to play the same animation in reverse, or play a new animation that i have created which is just a reverse of the first animation i play

i maybe using a C# wrong or not the right script, Very new to C#

and help would be greatly appreciated

You could use a bool instead of a trigger…

Here is a script that can probably work :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RiskAnimation : MonoBehaviour
{
public KeyCode MyKey;
public bool Risk;
public Animator animator;

 void Start()
{
   Animator = GetComponent<Animator>();
 }

 void Update()
 {
     if (Input.GetKey(MyKey))
     {

         Risk =! Risk;
         Animator.SetBool("PlayAnimation", Risk);
     }
 }

}

And in your Animator Controller make a loop between your two animations with the bool…
I think you know how work bool with animator… If not call me back !

Hope I helped !

Bye