This is how I did it when I was assigned a challenge not to jump infinitely, in case it would help someone.
Commented parts are about double jumping.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
Vector2 moveInput;
Rigidbody2D myRigidbody;
[SerializeField] int movementSpeed = 5;
[SerializeField] int jumpSpeed = 5;
bool flipX = false;
Animator myAnimator;
Collider2D myCollider2D;
bool canJump = false; // = true when touching Ground Layer (mask 64)
int jumpsAvailable; // Number of jumps available
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
Debug.Log(LayerMask.GetMask("Ground"));
myCollider2D = GetComponent<Collider2D>();
}
void Update()
{
Run();
GetComponent<SpriteRenderer>().flipX = flipX;
canJump = myCollider2D.IsTouchingLayers(64); // not sure if Rick did differently, just started a challenge
DoubleJump(); // because we love it in video games!
}
void Run()
{
Vector2 playerVelocity = new Vector2(moveInput.x * movementSpeed, myRigidbody.velocity.y);
myRigidbody.velocity = playerVelocity;
}
void DoubleJump()
{
if (canJump)
{
jumpsAvailable = 1; // jumps are available again after you touch the ground
}
}
void OnJump(InputValue value)
{
if (canJump || jumpsAvailable > 0) // || means OR
{
if (value.isPressed)
{
myRigidbody.velocity += new Vector2(0f, jumpSpeed);
jumpsAvailable--; // you've got only 1 more jump left until you touch the ground again
if (!canJump) Debug.Log("Double jump!"); // showing in console if we jumped while not touching the ground, can do it once because of our code
}
}
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
if (moveInput.x < 0)
{
flipX = true;
myAnimator.SetBool("isRunning", true);
}
else if (moveInput.x > 0)
{
flipX = false;
myAnimator.SetBool("isRunning", true);
}
else
{
myAnimator.SetBool("isRunning", false);
}
}
}