- Home /
Wanting to have a sprite animation to only start playing once the player collides with it?
This is a 2D game I'm working on. An example of what I'm trying to achieve is for a sprite animation to be frozen on it's first frame on startup, but its triggered to play out it's animation (only once) once the player collides with it. It must be very simple, but I'd consider myself a beginner to Unity3D
Answer by I_Am_Err00r · Aug 29, 2019 at 01:53 PM
If this object has any kind of Collider2D on it and the the player has any kind of Collider2D as well as a rigidbody, you could just do an OnCollisionEnter2D on the object you want to animate; so create a script (or you could use this one) and it should work (also, this requires you to have the player with tag "player" to work:
public class ExampleScript : MonoBehaviour
{
private Animation anim;
void Start()
{
anim = GetComponent<Animation>();
}
void OnCollisionEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Player")
{
anim.Play("WhateverYouCalledYourAnimation");
}
}
}
And to make sure that only plays once, I would also make sure on your animation file that you uncheck the box for loop (I believe it is set to true by default, which makes no sense to me).
THIS ISN'T TESTED WITH UNITY, I MIGHT NOT HAVE EVERYTHING RIGHT THERE, IF FOR SOME REASON IT GIVES YOU AN ERROR OR ISN'T DOING WHAT YOU NEED, PLEASE COMMENT TO THIS POST AND I WILL WALK YOU THROUGH IT.
Your answer
Follow this Question
Related Questions
why isn't my OnTriggerEnter2D() function working? 14 Answers
Why doesn't OnTriggerEnter2D get called? 1 Answer
Unity2D: Renderer off/ on by triggers 0 Answers
OnTriggerStay2D Breaks When Adding AnimationController 1 Answer
Collision returning an error 0 Answers