I need help with collision detection

Hey
I am trying to make a script that checks if the player is grounded so that the player can only jump when grounded,but it doesnt work,help me please

Here is my script:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour 
{

	//Movement
	public float speed;
	public float jump;
	float moveVelocity;

	//Grounded Vars
	bool grounded = true;

	void Update ()
	{
		//Jumping
		if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.Z) || Input.GetKeyDown (KeyCode.W)) {
			if (grounded) {
				GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
			}
		}

		moveVelocity = 0;

		//Left Right Movement
		if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) {
			moveVelocity = -speed;
		}
		if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) {
			moveVelocity = speed;
		}

		GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D> ().velocity.y);
	}

	void OnCollisionEnter(Collision collision) 
	{
		grounded = true;
	}

	void OnCollisionExit(Collision collision) 
	{
		grounded = false;
	}
}

Hi @HyP3R360!

The only problem there is on the void OnCollision.

The computer do the following:

If the object enters on a collision, grounded is true, if it exits, its false.

That means that every time it is on a collision, grounded is true.

You should do the following:

 void OnCollisionEnter(Collision collision) 
     {
if(collision.gameobject.name=="TerrainName")
{
         grounded = true;
}
     }
 
     void OnCollisionExit(Collision collision) 
     {
if(collision.gameobject.name=="TerrainName")
{
         grounded = false;
}
     }

I hope it works ^^