Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Unable to get the right animation transition via script.

Discussion in '2D' started by PilumMuralis, Jun 6, 2020.

  1. PilumMuralis

    PilumMuralis

    Joined:
    Jun 6, 2020
    Posts:
    12
    I want to transition from the default "idle animation" to a "jump animation" when the player gameobject is off the ground. The parameter in the animator for idle to jump animation is the bool "isOnGround" set to false. My animation is stuck constantly in "jump" even if the player hits the platform. I'm not even sure if it's a problem with my code or my logic at this point.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CharacterController2D : MonoBehaviour
    6. {
    7.     private bool isGrounded;
    8.     private Animator anim;
    9.  
    10.     void Start()
    11.     {
    12.         anim = GetComponent<Animator>();
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.      
    18.         if (isGrounded == true) {
    19.             anim.SetBool("isOnGround", true);
    20.         }          
    21.         else if (isGrounded == false) {
    22.             anim.SetBool("isOnGround", false);}
    23.     }
    24.  
    25.     void OnCollisionEnter(Collision2D collider) {
    26.         if (collider.gameObject.tag == "Ground") {
    27.             isGrounded = true;
    28.         }
    29.         else if (collider.gameObject.tag != "Ground") {
    30.             isGrounded = false;
    31.         }
    32.     }
    33. }
    34.  
     
  2. brigas

    brigas

    Joined:
    Oct 4, 2014
    Posts:
    522
    did you make a transition to go back to idle if grounded = true?
     
  3. PilumMuralis

    PilumMuralis

    Joined:
    Jun 6, 2020
    Posts:
    12
    Yup, there's such a transition.
     
  4. brigas

    brigas

    Joined:
    Oct 4, 2014
    Posts:
    522
    and when you look in inspector and you are on the ground does your bool isGrounded show true? and still stuck on jump anim?
     
  5. PilumMuralis

    PilumMuralis

    Joined:
    Jun 6, 2020
    Posts:
    12
    Oh i see the start of figuring something out. My bool shows isGrounded to be false and hence my animation is stuck as "jump". This is occurring despite my player object (with rb2d and boxcollider2d) being unable to fall further.
     
  6. PilumMuralis

    PilumMuralis

    Joined:
    Jun 6, 2020
    Posts:
    12
    I think I may have found the error. It was due to the method "OnCollisionEnter" instead of the correct "OnCollisionEnter2D". I'm not sure if this is the only problem I have, but for now things seem to be going accordingly. Thanks Brigas!
     
    brigas likes this.