play animation on keypress if in range

I dont seem to get this right at all…
Im trying to get/make a script that does, so when you are in range of an object with an animation (like a door), you press like “D”, and the door should open (Play the animation).
I’ve had some help before, but it didnt seem to work.
Here is the script i got as help, which didnt work:

public class AnimationTest : MonoBehaviour
{
	
    private Animation _anim;
    private bool closeEnough = false;

    void Start()
    {
        _anim = this.GetComponent<Animation>();
    }
 
    void Update()
    {
        if (Input.GetKeyDown("k") && closeEnough == true)
        {
            _anim.Play("Gate");
        }
    }
 
    void OnGUI()
    {
        if (Vector3.Distance(targetObject.transform.position, player.transform.position) < desiredDistance)
        {
            GUI.Label(new Rect(10, 10, 200, 20), "[k]");
            closeEnough = true;
        }
    }
}

And it would be nice having like a range of 5 or something.

Try using the Collider, for example if you have a sphere, set the sphere collider Range to 5 and set “Is Trigger” to True, so when your inside the collider and press k, the script will activate, I use this same method for sounds and doors. Script should be attached to the collider.

Something like this

void OnTriggerStay(Collider theCollider) {
		if(Input.GetKeyDown(KeyCode.E)) {
        doSomething
}}

Brackeys has a video tutorial which will walk you through setting up this scenario: Door Tutorial

Cheers

Make a cube and resize it the the size you want the range to be then put trigger on it then in the code put if collider blah blah blah