Beginner Question

I just recently started using Unity and am making a simple script that has a cube jump when you hit space. I tried to make it so you could only jump once until you were grounded again but for some reason you can jump twice (No more than twice) instead of once. Since the object starts at y = 0.5 I tried to make it so while it was above that you couldn’t jump. I know there are much easier ways to do this and I would like to know them but I was trying to figure it out myself.

Here is the code:

using UnityEngine;
using System.Collections;

public class JumpingCube : MonoBehaviour {

	public int jumpForce = 10;
	private bool grounded = true; 


	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

		if (grounded)
			if (Input.GetButtonDown ("Jump")) {
				grounded = false;
				GetComponent<Rigidbody> ().AddForce (0, jumpForce, 0); 
				 }

		if (transform.position.y <= .5)
			grounded = true;

				 


	
					}
}

I suggest using a Trigger collider under your GameObject and checking if it has been triggered to enable the “grounded” bool, as if it lands and it is higher than 0.5 in the y axis it wouldn’t jump.

Obviously, ignore this if that is irrelevant for your game :slight_smile:

Unity has a function for performing Rigidbody physics in an update loop. Try changing the function from

void Update()

to

void FixedUpdate()

Also, make that an else if for the second condition.