How to play animation only when being hit?

I’ve already figured out playing animation on hit but I’m wondering if it’s possible to play an animation by seconds only when it’s being collided with. Like if I collide with the object the animation starts but if I move away it stops mid animation. If I collide with it again the animation continues. How exactly would I do this?

Set Animator Speed to 0 when you want to pause it, and 1 when you want to continue playing the animation.

set a transition to exit your animation state in the animator. you can use the OnCollisionExit() to setup code to handle any animator parameters that you would like to use. And a reminder that OnCollisionEnter/stay/exit message will only be sent to a non kinematic ridigbody.