Selecting animation to play based on boolean

I’m trying to make a certain animation play when the player hits a trigger and presses a key. I have a boolean which gets changed depending on the animation that should be played. The problem is that it only ever plays one animation and I’m not sure why.

Could anyone help me find out the problem?

Updated code

var animObj : GameObject; //The game object I want to be animated

var nameAnim : String; //The name of the first animation
var nameAnim2 : String; //THe name of the "reverting" animation

var tagName : String; //If the animated object touches a trigger with this name, play an animation
var triggered = false;//Decides which animation is appropriate to play
var onTrig = false;


function OnTriggerEnter (other : Collider) //{

{
	if (other.gameObject.tag == tagName) //The player has touched the animated object
	{
		onTrig = true;
	}
}

function OnTriggerExit(other : Collider)
{
	onTrig = false;
}

function Update()
{

	if (onTrig == true)
	{
		if (Input.GetKeyDown ("e"))//If the player presses this key
		{ 
			if (!triggered)
			{
    			animObj.GetComponent.<Animation>().Play(nameAnim); //play the animation
    			triggered = true;
			}
	
			else if (triggered)
			{
				animObj.GetComponent.<Animation>().Play(nameAnim2); //Play the animation that brings the animated object back to the start
				triggered = false;
			}			
		}
	}
}

Ok, that’s a little strange setup. So OnTriggerStay can be called multiple times per frame. So expect that function to run a lot. Then, if you happen to hold down e, you’ll play an animation based on the bool, and invert the bool.

triggered will be switching true,false,true,false,true,false,true,false and so on many many times per second, and you’ll be starting the animation many times per second.

One suggestion would be to stop using GetKey, which will return true every frame you hold down the key and instead use GetKeyDown which will return true that frame you actually started holding down e. However this is likely still going to cause problems because OnTriggerStay can be called multiple times per frame, so your bool will still wiggle its value like a happy dogs tail, just in small bursts. If you run dry if project name suggestions; “Tail burst” could give you a fond memory of this dilemma. Anyway.

I’d move the Input and Animation code to Update instead of FixedUpdate for those reasons. Then I’d also no longer use OnTriggerStay but instead use OnTriggerEnter and OnTriggerExit to set a bool wether or not you are in a trigger or not.