Best / easiest way to play an animation after getting hit by a raycast

Hey,

I am trying to learn how to work with raycats and I wanted to make an openable locker / chest object wich would open after getting hit by a raycast. Currently I got it working that when I click, it shoots a ray forward with a max distance, and if it hits an “hittable” object it throws it into the air.

using UnityEngine;
using System.Collections;

public class Raycasting : MonoBehaviour {

	//Vars
	public float hitForce;
	public float objectDistance;

	void Update()
	{

		RaycastHit hit;
		Ray objectRay = Camera.main.ScreenPointToRay(Input.mousePosition);

		if (Input.GetMouseButtonDown (0)) 
		{
			if (Physics.Raycast (objectRay, out hit, objectDistance))
			{
				if (hit.collider.tag == "Hittable") 
				{
					hit.rigidbody.AddForce (Vector3.up * hitForce);
					print ("Found an hittable object");
				}
			} 
				
		}
	}
}

My question is, what is the best / easiest way for me to access the animator from the object that got hit, and play the animation needed.

Thanks,

I think if you do something like this after you confirmed it is a hittable:

Animator anim =  hit.collider.gameobject.GetComponent<Animator>();

Then if on the animator you have a bool “Open” to switch the state, you would set that bool, which would then run the state transitions within that specific animator.

//Make sure we actually got an animator
if(anim != null)
   anim.SetBool("Open", true);

There are various other ways you could do this as well, such as having a script on the objects and accessing that component and allowing them to handle this raycast hit behavior themselves. However, the above is about as simple as it gets in my opinion.