Open and closing a treasure chest with a keypress.

I would like to open and close a treasure chest with a keypress. When you approach the tresure chest a GUI will pop-up that say "PRESS X TO OPEN CHEST" ,and than the chest will stay open until you press the X button again to close it.

What's happening right now is I can open the chest but it will play both of the animation at the same time. It will open the chest and close the chest.

Can I make two saperate animation in one game object,example the chest(game object) has two animation inside it..open and closing.

This is my code:

private var chestIsOpen = false;
var hit : RaycastHit;

function Update(){ print(chestIsOpen);

`if(Physics.Raycast(transform.position, transform.forward, hit, 2))

{
if(hit.collider.gameObject.tag == “chest” );
var door = gameObject.FindWithTag(“chest”);

if (Input.GetKey ("x"))

{
chest.animation.Play(“open”);
chestIsOpen = false;

}

if (Input.GetKey ("x") && chestIsOpen == false)

{

  chest.animation.Play("close");
  chestIsOpen = true;

}

`

}

}

I think its Input.GetKeyDown

You are setting the chestIsOpen flag to false, then checking for the same flag in the next statement, closing the chest.

Try changing your code to the following...

var chestIsOpen = false;
var hit : RaycastHit;

function Update()
{
    print(chestIsOpen);

    if(Physics.Raycast(transform.position, transform.forward, hit, 2))
    {
        if(hit.collider.gameObject.tag == "chest" )
        {
            var chest = gameObject.FindWithTag("chest");
            if (Input.GetKeyDown("x"))
            {
                if  (chestIsOpen)
                {
                    chest.animation.Play("open");
                    chestIsOpen = false;
                } 
                else
                {
                    chest.animation.Play("close");
                    chestIsOpen = true;
                }
            }
        }
    } 
}

Hope this helps, -Larry