Stopping an animation clip after the player has passed the area.

Hello everyone!! I am playing certain clips on certain objects. In total there are 51 animation clips being played throughout the scene at a time. In order to optimize this I wrote following script :

function StartAnim(){
	hits = Physics.OverlapSphere(transform.position, 20);
	for(var i : int = 0; i < hits.Length; i++){
		if(hits*.transform.tag == "EditorOnly"){*

_ hits*.animation.Play(;_
_ if(hits.transform.tag == “GameController”){

This clip starts an animation only when player is around radius of 20.
Now in the same way as I have started animation clips I want to stop them once the player has passed away from that particular place. I could not make out on how to work out for this. Can anyone help me out for this problem. Thanks In Advance. Cheers._

Instead of OverlapSphere(), consider using OnTriggerEnter() and OnTriggerExit():

Give each object a sphere collider marked as “Is Trigger”. Set the radius of the sphere collider to be the distance at which the object should start playing animations. This allows you to fine-tune how close the player needs to be to each object. A large, highly-visible object might have a bigger radius than a tiny object.

Set the collision matrix (Edit > Project Settings > Physics) so the player’s collider will register collisions with the objects’ sphere colliders.

As the player’s collider enters each trigger, the physics system will send an OnTriggerEnter message to all components on the object and the player. In the object’s OnTriggerEnter(), check if the object is playing its animation. If not, start playing it.

function OnTriggerEnter(other : Collider) {
    if (!animation.isPlaying) {

When the player leaves the object’s trigger area, the physics system will send an OnTriggerExit message, at which point you can stop playing the animation:

function OnTriggerExit(other : Collider) {

Alternatively, you can make the player’s sphere collider a trigger instead. Either way, you can handle OnTriggerEnter/OnTrigger in a script on the player or the object since both get the message.