Playing animation when picking up an object.

So, I’ve been working hours by making scenes and editing my project. I’ve also managed to get a “key script” in order to proceed next scenes but there’s something else that I want to add. As the title says, I want an animation to play once my GameObject (Key) is removed from the scene after picking it up.

If you need more info, here’s my key script (Java):

Pick up script:

var hasKey = false;
 
function Update(){
if(Input.GetKeyDown(KeyCode.E)){ //If E is pressed
Debug.Log("Pressed");
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, hit, 100)) { // Sends out a raycast to check if something is in front of you
   	Debug.Log("hit Something " + hit.transform.name);
if(hit.transform.name.Equals("Key")){ // If the object in front of you has the tag Key
hasKey = true;
Destroy(hit.transform.root.gameObject);//Destroy Key Object
}else if(hit.transform.name.Equals("Door")){ //Checks if the gameobject you're looking at has the tag Door
if(hasKey)
Debug.Log("HasKey");
hit.transform.SendMessage("Unlock"); //Calls the function Unlock on the door
}
}
}
}

If you guys have a good way to solve this question, please leave an answer below! I would really appreciate it :slight_smile:

Thanks!

Try:

var hasKey = false;
 
function Update(){
if(Input.GetKeyDown(KeyCode.E)){ //If E is pressed
Debug.Log("Pressed");
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, hit, 100)) { // Sends out a raycast to check if something is in front of you
    Debug.Log("hit Something " + hit.transform.name);
if(hit.transform.name.Equals("Key")){ // If the object in front of you has the tag Key
hasKey = true;
Destroy(hit.transform.root.gameObject);//Destroy Key Object
animation.Play("myAnimation");
}else if(hit.transform.name.Equals("Door")){ //Checks if the gameobject you're looking at has the tag Door
if(hasKey)
Debug.Log("HasKey");
hit.transform.SendMessage("Unlock"); //Calls the function Unlock on the door
}
}
}
}

Put a Play animation after the key destroyed.

Sorry guys but this answer is really outdated… I’ve changed to this one: Playing animation when GameObject is destroyed - Questions & Answers - Unity Discussions