How do i use conditional if statements ?

Updated on August 5, 2019 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on August 3, 2019

So im making a script wherein if a object is collided with the player, the player does a new animation, 

 

 

 

then i want to do if the first condition is fufilled if a button is pressed then the animation plays, ive got the code down generally

 

 

 

 
 
 
private void OnTriggerEnter2D(Collider2D other)
 {
 if (other.gameObject.name == "Player" && (Input.GetKey("l")))
 {
 myanim.SetBool("coll", true);

 

 

 

How do i make it so if the game object collides and then if L is pressed then play the animation? 

  • Liked by
Reply
0 on August 5, 2019

You would need to store the collision when it happens so you could check it on later frames.

Then in your update loop, you check for that new tag you just set, AND if they press ‘L’.

 

bool hasCollided = false;
 
private void Update()
{
     // Pro tip, the double '&&' means that if the first condition fails,
     // it doesn't even bother checking the other one.
     if(hasCollided && Input.GetKeyDown(KeyCode.L))
     {
          hasCollided = false;
          myanim.SetBool("coll", true);
     }
}
 
private void OnTriggerEnter2D(Collider2D other)
 {
     if (other.gameObject.name == "Player")
     {
          hasCollided = true;
     }
}
  • Liked by
Reply
Cancel