Help! Trying to trigger animation.

Hello, let me start by saying I’m a beginner in all of this. I’ve been stuck for days on trying to make a simple script which will let me trigger an animation when my character runs over it. I don’t have a great knowledge on scripting language so I’ve been hunting around on the net for answers and scripts.

Specifically, I am trying to get a treasure chest to open when I walk over it. Ideally I’d like to to have a key be pressed which will open the chest but I can’t even get the script to work just by simply triggering the 2D Collider.

I have a 2d box collider on the chest checked for trigger, I added an Animation component with the animation in the box and the scripts I’ve found are placed on the object as well. I don’t understand what is wrong. I get messages saying that it cannot find the animation or animation state but I feel like those are fine (though that could be the problem). If I just had a script that for sure worked I could probably keep messing with it until it worked.

I just have 2 frames for the chest. One image that is a closed chest and another image that is an opened chest. I have it animated so that the sprite just changes from closed to open.

Any help is greatly appreciated, thanks.

Well, it’s certainly not going to be able to play the animation if it cannot find the animation. Maybe post the code and the object’s inspector information?

Here is the code I am using. I started testing this with simply colliding instead of using a trigger for now.

function OnCollisionEnter2D ( other : Collision2D ){

if (other.gameObject.tag == “Player”){

animation.Play(“chest”);

}

}

I was able to change the animation type to legacy by going into the debug menu and changing the animation from 2 to 1. My animation still never changed sprites like it was supposed to. I was curious, instead of doing a sprite change I had the closed chest simply move to the right and that worked perfectly. The code works, but the sprite just will not change like it needs to.

I have the closed chest as an object in the hierarchy attached with Transform, Sprite Renderer, the script, box collider2d, and an Animation component equipped with the “chest” animation. Like I said, I can get an animation to work with this script but the sprites just won’t swap out like I want it to.