Script Help

I need help on a 2d player controller script in C#, for some reason the player can jump as many times as they want up to the point where they are 1 tick (I don’t know what to call the values :?) above the block in the Y axis, any help? Here is the script:

using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour
{
	public float moveSpeed = 1;
	public float jumpSpeed = 10;
	
	private bool isFalling = false;
	private float RayCastModifier = 0.01f;
	
	void Update()
	{
		if (Input.GetKey(KeyCode.D))
		{
			transform.position += (transform.right * moveSpeed) * Time.deltaTime;   //We're multiplying with deltaTime so that higher framerate != higher speed.
		}
		else if (Input.GetKey(KeyCode.A))
		{
			transform.position -= (transform.right * moveSpeed) * Time.deltaTime;
		}
		RaycastHit2D hit = Physics2D.Raycast (transform.position, -Vector2.up, transform.lossyScale.y + RayCastModifier, 1 << LayerMask.NameToLayer("Environment"));
		Debug.Log(hit.collider);
		if (hit.collider != null)
		{
			isFalling = false;
		}
		else
		{
			isFalling = true;
		}
		
		if (Input.GetKeyDown(KeyCode.Space)  isFalling == false)
		{
			if (GetComponent<Rigidbody2D>())
			{
				rigidbody2D.AddForce(Vector2.up * jumpSpeed);
			}
			else
			{
				Debug.LogError("You're trying to access a Rigidbody2D component but " + gameObject.name + " doesn't have it!");
			}
		}
	}
}

You need to check if hit is null.

If the raycast doesn’t hit anything, it returns null. Any attempt to access a null value will fail, throwing an exception and stopping the rest of your Update code from running.

You need to replace this code:

        Debug.Log(hit.collider);
        if (hit.collider != null)
        {
            isFalling = false;
        }
        else
        {
            isFalling = true;
        }

With something more like this:

        if (hit == null) 
        {
            isFalling = true;
        }
        else
        {
            Debug.Log(hit.collider);
            isFalling = false;
        }

After doing that, it made the player possible to jump as many times as they want no matter want…

RaycastHit2D is a struct so it won’t be null. If you read the documentation you’ll notice that the collider field will be null if nothing is hit.

The player can jump when they are 1 unit above the ground because that’s the length of your ray (-Vector3.up). Raycast a smaller distance - like to the bottom of the character - for better results.