2D Sprite not Jumping

So I first made a script, and my 2D Sprite would bounce, but he would be able to bounce infinitely. I added a string to check for collision but now it doesn’t jump at all. And before I get answers like “Did you make sure you tagged the ground with the correct tag”,
yes I did. Everything is tagged correctly and console is not showing any messages but my sprite isn’t jumping.

#pragma strict

var jumpSpeed = 8;


function OnCollisionStay (collision : Collision) {
     
      if (collision.gameObject.tag == "Ground2D" && Input.GetKeyDown(KeyCode.Space))
   {
   GetComponent.<Rigidbody2D>().velocity.y = jumpSpeed;
   }
}

“OnCollisionStay()” is based around “FixedUpdate()”. “FixedUpdate()” has separate timing from “Update()”.

Why does this matter? Keyboard input is drawn from Update(), which means that GetKeyDown(), as a call only registered on the first Update() frame after the input occurs, easily and often is missed by FixedUpdate(), let alone OnCollisionStay().

However, there is also a second problem here: You probably need to be calling “OnCollisionStay2D()” for your game, judging by the rest of the context of your script.

To handle the timing and reliability issues you’ll surely run into once you do make that change, however, I would recommend testing your collider in OnCollisionStay2D() for its tag. If the tag is “Ground2D”, set a boolean “grounded” variable to true and a boolean “jumping” to false. Then, in Update(), if you’re grounded and GetKeyDown(KeyCode.Space)), set “jumping” to true. Finally, in FixedUpdate(), if “jumping” is true, change your velocity, set grounded to false and jumping to false (because the trigger to jump is now past).

Why all the complexity? FixedUpdate() handles the physics of the Rigidbody, but Update() handles control input. If you mix them up, you can easily wind up with unintended results based on luck and timing.

private var jumping: boolean;
private var grounded: boolean;

function Update()
{
	if(grounded && Input.GetKeyDown(KeyCode.Space))
	{
		jumping = true;
	}
}

function FixedUpdate()
{
	if(grounded && jumping)
	{
		GetComponent.<Rigidbody2D>().velocity.y = jumpSpeed;
		jumping = false;
		grounded = false;
	}
}

function OnCollisionStay2D(collision: Collision2D)
{
	if(collision.gameObject.CompareTag("Ground2D"))
	{
		grounded = true;
	}
}

function OnCollisionExit2D(collision: Collision2D)
{
	// A safety, just in case you walk off a cliff instead
	grounded = false;
}