Help With Jump Script (C#)

Hi Guys,

I have a problem with my jump script, i can jump normally. but sometimes my player jumps to high randomly high.
is there a problem with my script.

using UnityEngine;
using System.Collections;

public class Jump : MonoBehaviour {
	public bool grounded = true;
	public float jumpPower = 190;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
			// Do something
			
	


		if(!grounded && rigidbody2D.velocity.y == 0) {
			grounded = true;
		}
		if (Input.GetButtonDown("Fire1") && grounded == true) {
			rigidbody2D.AddForce(transform.up*jumpPower);
			grounded = false;
		}
	}
}

Thank You

AddForce only changes the velocity during fixed update. Fixed update never runs faster then 60 FPS. Update on the other hand will run as fast as it can. Even if it only runs at 61 FPS then every now and then it will run twice before FixedUpdate runs. Forces added are queued until FixedUpdate runs.

This is what is most likely happening:

Update() runs. The character is standing still so grounded returns true. A force is added, but the character does not move.

Update() runs. The character is still standing still, so grounded returns true. Another force is added, character still does not move.

FixedUpdate() runs. All queued forces are added to the character and the character jumps twice as high.

Here is a code to fix to try (C#, untested):

using UnityEngine;
using System.Collections;
 
public class Jump : MonoBehaviour {
    public bool grounded = true;
    public float jumpPower = 190;
    private bool hasJumped = false;

    // Use this for initialization
    void Start () {
    }
 
    // Update is called once per frame
    void Update () {
       // Do something
 
       if(!grounded && rigidbody2D.velocity.y == 0) {
          grounded = true;
       }
       if (Input.GetButtonDown("Fire1") && grounded == true) {
         hasJumped = true;
       }
    }

    void FixedUpdate (){
        if(hasJumped){
            rigidbody2D.AddForce(transform.up*jumpPower);
            grounded = false;
            hasJumped = false;
        }
    }
}

perhaps it’s a wee bit too late but if you can get the player object to check the ground object’s tag, (OnCollision function) you can turn jump on and off with a bool. if it’s colliding with this object with this specific tag you can jump. If not, you can’t. check if bool == true && collision tag = “thistag” jump else !jump.

hope this helps someone else out in the future.