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

Question my isgrounded variable isn't working as intended so I get infinite jumps.

Discussion in 'Scripting' started by Armadillosleepspillow645, Feb 22, 2023.

  1. Armadillosleepspillow645

    Armadillosleepspillow645

    Joined:
    Apr 26, 2022
    Posts:
    1
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class playerJump : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.  
    9.     bool IsGrounded;
    10.     public Rigidbody rb;
    11.     public float jumpForce;      
    12.     void Start()
    13.     {
    14.         IsGrounded = true;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.  
    21.         if (IsGrounded = true && Input.GetKeyDown(KeyCode.Space) == true)
    22.         {
    23.             IsGrounded = false;
    24.             rb.velocity = Vector2.up * jumpForce;
    25.          
    26.        
    27.  
    28.         }
    29.     }
    30. }
     
  2. Rin-Dev

    Rin-Dev

    Joined:
    Jun 24, 2014
    Posts:
    557
    From what you posted I don't see why it wouldn't set the grounded bool to false after the first press.

    Use Debug logs to see if anything else is affecting your isgrounded bool.
    Easiest way I could think of would be-
    Code (CSharp):
    1.  private bool isGrounded;
    2. public bool IsGrounded{
    3.      get { return isGrounded; }
    4.      set {
    5.              isGrounded = value;
    6.              Debug.LogFormat ("Changed!");
    7.      }
    This way you can check the console and see what is changing it, if anything at all.
     
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,856
    Issue lies here:
    Code (CSharp):
    1. if (IsGrounded = true
    You use one
    =
    for assignment, two
    ==
    for comparison.

    Right now you're assigning
    true
    to
    isGrounded
    , rather than checking if
    isGrounded
    is true.

    It should be
    if (isGrounded == true)
    or even just
    if (isGrounded)
    .
     
    Rin-Dev likes this.