- Home /
Simple animation script not working (C#)
Hi I have a script for when my player is hit by a bullet he plays a dying animation then the object is destroyed. But the script isn't working i have added an animator to the player but still nothing happens. all that happens is the object getting destroyed and the animation not playing.
CODE
public GameObject player;
public Animator animation;
void Start () {
animation = GetComponent<Animator> ();
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Bullet")
{
animation.Play("Dying");
Destroy(player);
}
}
You're destroying the player the instant the animation starts playing. Change your code so the object is destroyed after the animation is finished.
Answer by wesleywh · Jul 14, 2015 at 07:05 PM
So I take it that you want the animation to play THEN have your player destroyed. Just like it has been already said your immediately destroy your player after you start you animation. For all I know your animation could be playing but you destroy your player so fast you will never see it. Simply add a delay before you destroy your player or check to make sure your animation is done or in a certain state.
void Start () {
animation = GetComponent<Animation> ();//notice this isn't Animator, there is a big difference between the two
}
void OnTriggerEnter2D(Collider2D col){
if(col.gameObject.tag == "Bullet")
{
StartCoroutine(playDeath(5.0f));
}
}
IEnumerator playDeath(delayTime:float){
animation.Play("Dying");
yield return new WaitForSeconds(delayTime);
Destroy(player);
}
So do you want to use Animator(new $$anonymous$$echam Animations) or Animation(Legacy Animation)?
I fixed my code. Wrote it wrong. Anyway, you can't use "animation.Play". You will have to setup animation states and use the following in your code:
anim.SetBool("isDead", true);//this is simply true go to the dead state from your current state
Or something equivalent to it. Unity has a very good tutorial going very in depth about this. The one that I learned from is here(Its out of date, unity 4 but still applicable):
https://www.youtube.com/watch?v=Xx21y9eJq1U
Or from the live training one that is found here:
https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/animate-anything
Your answer
Follow this Question
Related Questions
How do I know when an object is going under a Platform Effector 2D object? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to add keyframe animation to an imported FBX. 0 Answers
Animation at the end of the level 1 Answer