How to properly play an animation clip in 2D Game

Hello fellow game makers, I need to play an animation after my character collides with a trigger. Simple right ? Well please help me figure this out ! Thanks in advance.

Note: This is a 2D game so what ever suggestions you have remember it’s 2D.

Also, please be very descriptive with your explanations, help me understand.


using UnityEngine;
using System.Collections;

public class nameofyourscript : MonoBehaviour {

void OnTriggerEnter2D (Collider2D other)
	if (other.gameObject.tag == "Player") 
		Debug.Log ("Yay!");  // just in case your animation doesn't work.
		GetComponent<Animation>()["Nameofanimation"].wrapMode = WrapMode.Once;
                    Destroy (gameObject,20);    // Do you want to destroy the object? 


So attach a script like this on on your trigger object. After doing that, make sure you check the trigger on both your character and the trigger object.

Also something you have to do is give your trigger object a “Rigidbody2D”.

Something else I want to add just in case someone ever has this question is that the animation doesn’t have to have a “Animator” component. In my case, it just needed an animation attached to it.

I hope I was able to help someone out there.