2D Raycast not working as intended

Huy guise, I’m in the process of teaching myself Unity (2D), and I have a bit of a problem…
I only have two script files, all attached to the player gameobject sprite thing. One of them is a left and right movement script, and the other one allows jumping. The jump script is the problematic one:

public class Jump : MonoBehaviour 
{
	public bool YN = false;
	public float jmppwr = 10f;

	void Update()
	{
		RaycastHit2D ground = Physics2D.Raycast(transform.position, -Vector2.up, 1);
		if (ground != null) 
		{
			YN = true;
		}
	}

		void FixedUpdate()
	{
		if (Input.GetKey(KeyCode.Space) && YN)
		{
			rigidbody2D.AddForce(new Vector2(0f, jmppwr));
			YN = false;
		}
	}
}

The issue is that bool YN is always true (even when there’s no ground collision object underneath), hence allowing the player to jump mid-air and stuff.
Anyone know what the problem is?

One problem is that you never set ground to false. Once YN is set to true, it stays true even if the ground is no longer there. It only get set to false after a jump is started. A quick fix using your current structure would be:

 if (ground != null) 
   {
     YN = true;
   }
else {
   YN = false;
}

But that is equivalent to:

YN = (ground != null);

Here’s final working script in case somebody in the future might need it

public class Jump : MonoBehaviour 
{
	public GameObject groundCheck;
	public bool ground = false;
	public float jmppwr = 10f;
	public float rayl = 1f;
	void Awake()
	{
		groundCheck = GameObject.Find("groundCheck");
	}

	void Update()
	{
		ground = Physics2D.Raycast(groundCheck.transform.position, -Vector2.up, rayl);
	}
	
	void FixedUpdate()
	{
		if (Input.GetKey(KeyCode.W) && ground)
		{
			rigidbody2D.AddForce(new Vector2(0f, jmppwr));
		}
	}
}