- Home /
How to trigger an animation from a prefab?
I have some looting items that need to be picked up. Some of them are in the ground but others are at a higher level and I would like the item picked to set the corresponding animation.
public class WaterBottle : MonoBehaviour
{
public GameObject playerObject;
public Animator playerAnimator;
void Start()
{
playerObject = GameObject.FindGameObjectWithTag("Player");
playerAnimator = playerObject.GetComponent<Animator>();
}
void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("Looks like a bottle of water...");
}
}
void OnTriggerStay(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("Press E to pick it up");
if(Input.GetKey(KeyCode.E))
{
playerAnimator.SetFloat("Side", -0.5f);
playerAnimator.SetTrigger("Pickup");
Destroy(this.gameObject);
Debug.Log("You've picked up a bottle of water");
}
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("Yes, probably is not a good idea anyway...");
}
}
}
In this case, the WaterBottle is a prefab with a trigger collider that succesfully detects the correct GameObject and Animator component, yet it fails to set the parameters but shows no errors. The object gets picked up and destroyed, but the pickup animation is not performed.
Any hints?
Answer by tanyanzhi · May 30, 2015 at 11:36 AM
you can destroy the gameobject after one second and create a bool value:deadFlag:
if(deadFlag == false){
playerAnimator.SetFloat("Side", -0.5f);
playerAnimator.SetTrigger("Pickup");
Destroy(this.gameObject, 1f);
Debug.Log("You've picked up a bottle of water");
deadFlag = true;
}
Thank you.
The problem, as usual was the animation, which was idling for a second before actually doing the pickup motion.
try use function Invoke to delay a second:
void OnTriggerStay(Collider other)
{
if(other.tag == "Player")
{
Debug.Log("Press E to pick it up");
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.E))
{
if(deadFlag == false){
playerAnimator.SetTrigger("idle");
Invoke("Pickup", 1f);
deadFlag = true;
}
}
}
}
void Pickup() {
playerAnimator.SetFloat("Side", -0.5f);
playerAnimator.SetTrigger("Pickup");
Destroy(this.gameObject, 1f);
Debug.Log("You've picked up a bottle of water");
}