Play animation on keypress when in range.

Hi im new in unity and i have a problem with a door.I want to play an animation when i press an key when the player is in range pls help me.

It is pretty simple, I hope you know how to make animations already, remember to add a bool parameter to your door animator and make transitions between closing and opening animation (there’s a tutorial for this - YouTube) :slight_smile: Also uncheck “Loop time” on your open and close animations so it will play only once. Then, tag all your door objecs as “Door”. The script is measuring the distance between player and every door object, then checks which one is closest to your player and plays open or close animation on key pressed when in range :slight_smile: there’s a code (it may look a bit complicated but it’s really not that hard to understand)
This is a script that every door must have:

	bool open = false;
	Animator anim;
	// Use this for initialization
	void Start()
	{
		anim = this.gameObject.GetComponent<Animator> ();
	}
	public void openOrCloseTheDoor() //A very simple function to open or close the door
	{
		if (open) {
			open = false;
			anim.SetBool ("open", open);
			print ("close");
		} else {
			open = true;
			anim.SetBool ("open", open);
			print ("open");
		}
	}
}

And there’s a code that your player must have:

	public float range = 5f; //Your range to open the door
	GameObject[] Doors; //Array that contains every door object in scene

	void Start()
	{
		Doors = GameObject.FindGameObjectsWithTag ("Door"); //finds every door
	}

	void Update()
	{
		if (Input.GetKeyDown (KeyCode.F)) {
			if(Vector3.Distance(transform.position, GetClosestDoor().position) <= range) //Checks which door is closest and if it is in range
			{
				GetClosestDoor ().GetComponent<doorScript> ().openOrCloseTheDoor (); //Get closest door and open or close it
			}
		}
	}

	Transform GetClosestDoor()
	{
		var closestDist = Mathf.Infinity; //a variable that resets back to infinity everytime this function is called, any other distance will be smaller than infinity
		var closestDoor = Doors[0]; //just another temp variable
		for (int i = 0; i < Doors.Length; i++) { //a loop that goes thru every door
			var distToIDoor = Vector3.Distance (this.transform.position, Doors _.transform.position); //Gets distance to Doors *object*_

* if (distToIDoor < closestDist) { //check if current door in the loop is closer than previous closest one*
* closestDist = distToIDoor;*
_ closestDoor = Doors*;
}
}
return closestDoor.transform; //returns which door is closest to your player*
* }*_