Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Jump Animation breaks when turning my player into a prefab

Discussion in '2D' started by pipose48, May 22, 2023.

  1. pipose48

    pipose48

    Joined:
    Feb 23, 2020
    Posts:
    3
    I'm currently working on a 2D Platformer in Unity. I followed along Brackeys Tutorials (will post links below) and everything works like intended, except when I turn my Player Object into a prefab. Then suddenly my Jump Animation breaks for some reason. Does anyone know a solution for this problem, because im not sure whether it's a programming problem or a unity related issue.

    Tutorials I used:

    #1

    #2


    Bugged Animation video:


    The left player character in the video is the prefab with the bugged animation.

    Would be really awesome if someone can help me :)

    This is my PlayerMovement.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     public CharacterController2D controller;
    8.  
    9.     float horizontalMove = 0f;
    10.  
    11.     public float runSpeed = 40f;
    12.     bool jump = false;
    13.     bool crouch = false;
    14.     public Animator animator;
    15.  
    16.  
    17.     public float coyoteTime = 0.2f;
    18.     public float coyoteTimeCounter = 0;
    19.  
    20.     public float jumpBufferTime = 0.2f;
    21.     public float jumpBufferCounter;
    22.  
    23.     // Update is called once per frame
    24.     void Update()
    25.     {
    26.         horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
    27.  
    28.         animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
    29.  
    30.         if (controller.m_Grounded)
    31.         {
    32.             coyoteTimeCounter = coyoteTime;
    33.         }
    34.         else
    35.         {
    36.             coyoteTimeCounter -= Time.deltaTime;
    37.         }
    38.  
    39.         if (Input.GetButtonDown("Jump"))
    40.         {
    41.             jump = true;
    42.             animator.SetBool("IsJumping", true);
    43.             jumpBufferCounter = jumpBufferTime;
    44.         }
    45.         else
    46.         {
    47.             jumpBufferCounter -= Time.deltaTime;
    48.         }
    49.  
    50.         if (Input.GetButtonUp("Jump"))
    51.         {
    52.             coyoteTimeCounter = 0f;
    53.         }
    54.  
    55.         if (Input.GetButtonDown("Crouch"))
    56.         {
    57.             crouch = true;
    58.         }
    59.         else if (Input.GetButtonUp("Crouch"))
    60.         {
    61.             crouch = false;
    62.         }
    63.     }
    64.  
    65.     public void OnLanding()
    66.     {
    67.         animator.SetBool("IsJumping", false);
    68.     }
    69.  
    70.     public void OnCrouching(bool isCrouching)
    71.     {
    72.         animator.SetBool("IsCrouching", isCrouching);
    73.     }
    74.  
    75.     private void FixedUpdate()
    76.     {
    77.         controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump, jumpBufferCounter);
    78.         jump = false;
    79.     }
    80. }
    and this is my CharacterController2D.cs

    Code (CSharp):
    1. using Unity.VisualScripting;
    2. using UnityEngine;
    3. using UnityEngine.Events;
    4.  
    5. public class CharacterController2D : MonoBehaviour
    6. {
    7.     [SerializeField] private float m_JumpForce = 400f;                          // Amount of force added when the player jumps.
    8.     [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%
    9.     [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f;  // How much to smooth out the movement
    10.     [SerializeField] private bool m_AirControl = false;                         // Whether or not a player can steer while jumping;
    11.     [SerializeField] private LayerMask m_WhatIsGround;                          // A mask determining what is ground to the character
    12.     [SerializeField] private Transform m_GroundCheck;                           // A position marking where to check if the player is grounded.
    13.     [SerializeField] private Transform m_CeilingCheck;                          // A position marking where to check for ceilings
    14.     [SerializeField] private Collider2D m_CrouchDisableCollider;                // A collider that will be disabled when crouching
    15.  
    16.     const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
    17.     public bool m_Grounded;            // Whether or not the player is grounded.
    18.     const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up
    19.     private Rigidbody2D m_Rigidbody2D;
    20.     private bool m_FacingRight = true;  // For determining which way the player is currently facing.
    21.     private Vector3 m_Velocity = Vector3.zero;
    22.     private PlayerMovement player;
    23.  
    24.  
    25.     [Header("Events")]
    26.     [Space]
    27.  
    28.     public UnityEvent OnLandEvent;
    29.  
    30.     [System.Serializable]
    31.     public class BoolEvent : UnityEvent<bool> { }
    32.  
    33.     public BoolEvent OnCrouchEvent;
    34.     private bool m_wasCrouching = false;
    35.  
    36.     private void Awake()
    37.     {
    38.         m_Rigidbody2D = GetComponent<Rigidbody2D>();
    39.         player = GetComponent<PlayerMovement>();
    40.  
    41.         if (OnLandEvent == null)
    42.             OnLandEvent = new UnityEvent();
    43.  
    44.         if (OnCrouchEvent == null)
    45.             OnCrouchEvent = new BoolEvent();
    46.     }
    47.  
    48.     private void FixedUpdate()
    49.     {
    50.         bool wasGrounded = m_Grounded;
    51.         m_Grounded = false;
    52.  
    53.         // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
    54.         // This can be done using layers instead but Sample Assets will not overwrite your project settings.
    55.         Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
    56.         for (int i = 0; i < colliders.Length; i++)
    57.         {
    58.             if (colliders[i].gameObject != gameObject)
    59.             {
    60.                 m_Grounded = true;
    61.                 if (!wasGrounded)
    62.                     OnLandEvent.Invoke();
    63.             }
    64.         }
    65.     }
    66.  
    67.     private void OnTriggerStay2D(Collider2D other)
    68.     {
    69.         if (other.CompareTag("Water"))
    70.         {
    71.             m_Grounded = true;
    72.             m_JumpForce = m_JumpForce = 800;
    73.             m_Rigidbody2D.gravityScale = 0.8f;
    74.         }
    75.     }
    76.  
    77.  
    78.     private void OnTriggerExit2D(Collider2D other)
    79.     {
    80.         if (other.CompareTag("Water"))
    81.         {
    82.             m_Rigidbody2D.gravityScale = 3f;
    83.             m_JumpForce = 800;
    84.         }
    85.     }
    86.  
    87.     public void Move(float move, bool crouch, bool jump, float jumpBufferTimer)
    88.     {
    89.         // If crouching, check to see if the character can stand up
    90.         if (!crouch)
    91.         {
    92.             // If the character has a ceiling preventing them from standing up, keep them crouching
    93.             if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
    94.             {
    95.                 crouch = true;
    96.             }
    97.         }
    98.  
    99.         //only control the player if grounded or airControl is turned on
    100.         if (m_Grounded || m_AirControl)
    101.         {
    102.  
    103.             // If crouching
    104.             if (crouch)
    105.             {
    106.                 if (!m_wasCrouching)
    107.                 {
    108.                     m_wasCrouching = true;
    109.                     OnCrouchEvent.Invoke(true);
    110.                 }
    111.  
    112.                 // Reduce the speed by the crouchSpeed multiplier
    113.                 move *= m_CrouchSpeed;
    114.  
    115.                 // Disable one of the colliders when crouching
    116.                 if (m_CrouchDisableCollider != null)
    117.                     m_CrouchDisableCollider.enabled = false;
    118.             } else
    119.             {
    120.                 // Enable the collider when not crouching
    121.                 if (m_CrouchDisableCollider != null)
    122.                     m_CrouchDisableCollider.enabled = true;
    123.  
    124.                 if (m_wasCrouching)
    125.                 {
    126.                     m_wasCrouching = false;
    127.                     OnCrouchEvent.Invoke(false);
    128.                 }
    129.             }
    130.  
    131.             // Move the character by finding the target velocity
    132.             Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y);
    133.             // And then smoothing it out and applying it to the character
    134.             m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
    135.  
    136.             // If the input is moving the player right and the player is facing left...
    137.             if (move > 0 && !m_FacingRight)
    138.             {
    139.                 // ... flip the player.
    140.                 Flip();
    141.             }
    142.             // Otherwise if the input is moving the player left and the player is facing right...
    143.             else if (move < 0 && m_FacingRight)
    144.             {
    145.                 // ... flip the player.
    146.                 Flip();
    147.             }
    148.         }
    149.         // If the player should jump...
    150.         if (player.coyoteTimeCounter > 0f && jumpBufferTimer > 0f)
    151.         {
    152.             // Add a vertical force to the player.
    153.             m_Grounded = false;
    154.             m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
    155.             player.jumpBufferCounter = 0f;
    156.         }
    157.     }
    158.  
    159.  
    160.     private void Flip()
    161.     {
    162.         // Switch the way the player is labelled as facing.
    163.         m_FacingRight = !m_FacingRight;
    164.  
    165.         // Multiply the player's x local scale by -1.
    166.         Vector3 theScale = transform.localScale;
    167.         theScale.x *= -1;
    168.         transform.localScale = theScale;
    169.     }
    170. }
    Kind Regards,

    Jean-Pierre
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,298
    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.