Double Jumping in Unity - Fix Infinite Jumping
Published on July 18, 2025Add double jumping in Unity
Code Snippets
Move.cs
New fields:
[SerializeField] int maxJumps = 2;
[Header("Ground Check")] [SerializeField]
LayerMask groundMask;
[SerializeField] float groundCheckSize = 0.5f;
int _jumpCount = 0;
Ground Check:
bool IsGrounded
{
get
{
var hit = Physics2D.Raycast(
transform.position,
Vector2.down,
groundCheckSize,
groundMask);
if (!hit || !hit.collider)
{
return false;
}
_jumpCount = 0;
return true;
}
}
New Jump Logic
if (Input.GetKeyDown(KeyCode.Space)
&& (IsGrounded || _jumpCount < maxJumps))
{
rigidbody2d.angularVelocity = 0;
rigidbody2d.linearVelocityY = 0;
_jumpCount++;
rigidbody2d.linearVelocityY = jumpPower;
}
OnDrawGizmos
void OnDrawGizmos()
{
Gizmos.DrawRay(transform.position, Vector3.down * groundCheckSize);
}