C# | How to disable gravity for a certain amount of time?

Okay, so I’m making my own jumping script ( a very simple one), and I need to disable the gravity feature for like maybe 0.5 or 1 second for it to work. I just don’t know how to do it. Also, I’m a beginner so please explain in depth what’s happening in the code so that I can understand.

     void Update () {
        		if (Input.GetKey (KeyCode.Space)) 
        		{
        			transform.Translate (Vector3.up * 5 * Time.deltaTime);
        		}
}

This seems like a strange way to implement a jump, normally gravity doesn’t disappear as you leap into the air! But if that is what you want to do, use a coroutine. A coroutine just allows you to run a second lot of code ‘parallel’ to the other code being executed, rather than the usual, one method, then the next. Note that the code here doesn’t run in a new thread, it simply ‘saves’ its state at the end of each frame, and continues where it left off in the next one:

bool isJumping = false;
Rigidbody rb;

void Update(){
	//some code

	if(someAction && !isJumping){ //if someAction was performed and we are not already jumping, start!
		StartCoroutine(Jump(rb));
	}
}

IEnumerator Jump(Rigidbody rigidbody){
	isJumping = true; //make sure we can't jump whilst already doing so!
	bool oldGravity = rigidbody.useGravity; //save our old gravity
	rigidbody.useGravity= false; //set gravity to 'not used'

	float timer = 0.5f //set the time for which to hold gravity off

	while(timer >= 0){
		//do some jumping stuff

		timer -= Time.deltaTime; //minus the time that the frame took, from our timer i.e. count down
		yield return null; //move to the next frame
	}

	//our time is up
	rigidbody.useGravity = oldGravity; //set gravity back to normal

	//might want to wait until we hit the floor again or something, before allowing ourselves to jump again
	isJumping = false;
}

Using Translate for movement with when physics is involved is generally a bad idea. Secondly, turning off gravity, will effect ever rigidbody’s gravity, not just the player that is jumping… more design floors, best just to use AddForce or similar, or set rigidbody.velocity over the course of a few frames if you really want a set ascent speed.

Anyway… you have been warned!