How to play an animation when collision?

I am trying to figure out how triggered animations work.

So I have this cube in my scene, with it an animation called “Cube1Anim” (pos. transform).
I have a script attached to that cube which starts with animation.Stop("Cube1Anim"); to stop the animation right at the beginning.

That’s the first problem, since I get following error:

MissingComponentException: There is no Animation' attached to the "Cube"

So how can I

  1. Stop the animation by default
  2. Play it when the Player collides with it.

I don’t have much experience with animation but if you dont want it to play right away i think you can click on the cube go to the inspector>animation and uncheck play automatically.

for the animation to play when the player collides i would attack a script

public class whatever : MonoBehaviour {
	public Animation youranimation;
	void OnCollisionEnter() {
		youranimation.Play();
     }
}

attach this to your object, then from the inspector Drag your animation into youranimation in the script
I hope this works

you could also maybe do: (but im not sure)

public class whatever : MonoBehaviour {
     Animation youranimation = GetComponent<Animation> ();
    void OnCollisionEnter() {
        youranimation.Play();
     }
}

and skip the dragging and dropping part.

First and foremost if you want to play animation once per collision you should mark it as triggered animation. So in animator view you make from default transition to your animation called lets say “CubeAnimation”. Click on transition and make parameter as Trigger call it whatever you want. Now lets get it in code.

void OnCollisionEnter(Collision collision){
    if(collision.CompareTag("TAG_ATTACHED_TO_YOUR_OBJECT"){
         animator.SetTrigger("NAME_OF_YOUR_TRIGGER_PARAMETER");
     }
}

Also make sure animation doesnt have loop checked and autoplay.
Good luck!