Animation play only when in range

I am new to both unity and java script, so I’m having some trouble. I have an object with an animation (Take 001). I want this animation to play and loop only when it’s within a certain range of the object tagged ‘player’. When it’s out of range I want the animation to stop. I found a few similar questions to this on here, but didn’t give me quite what I was looking for.

hallo

add this script at the object, if don’t rotate only remove part relative the rotation

in hierarchy set range and add the animation

Something like this?

using UnityEngine;

class PlayAnimation : MonoBehaviour
{
    public float range = 5;
    private Transform player;

    void Start()
    {
        player = GameObject.FindWithTag("Player").GetComponent<Transform>();
    }

    void Update()
    {
        if (Vector3.Distance(player.position, transform.position) < range)
        {
            if (!animation.isPlaying) animation.Play();
        }
        else
        {
            if (animation.isPlaying) animation.Stop();
        }
    }
}