Toggle Gravity on button press

I’m creating a side scroller where the Gravity of the player is a gameplay mechanic.

The initial gravity value is negative (falling downwards) and when the player presses the G key, the gravity changes to positive (floating upwards).

The script toggles a boolean value on/off when the G key is pressed. This part of the code works.

If the boolean is false(off) then the gravity should be -

if the boolean is true (on) then the gravity is equal to a antigrav variable (+gravity).

I can get the gravity to toggle so that the players gravity changes to positive, but I cannot change it back. Even though the boolean variable continues to toggle on/off.

[RequireComponent (typeof (Controller2D))]
public class Player : MonoBehaviour {

	public float jumpHeight = 4;
	public float timeToJumpApex = .4f;
	float accelerationTimeAirborne = .2f;
	float accelerationTimeGrounded = .1f;
	float moveSpeed = 6;

	public bool antigravTrue = false;
	float antigrav;
	float gravity;
	float jumpVelocity;
	Vector3 velocity;
	float velocityXSmoothing;

	Controller2D controller;

	void Start () {
		controller = GetComponent<Controller2D> ();
		gravity = -(2 * jumpHeight)/Mathf.Pow (timeToJumpApex, 2);
		antigrav = (2 * jumpHeight)/Mathf.Pow (timeToJumpApex, 2);
		jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
		print ("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity);


	void Update(){

		if (controller.collisions.above || controller.collisions.below){
			velocity.y = 0;

		Vector2 input = new Vector2(Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));

		if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.below){
			velocity.y = jumpVelocity;

		if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.above){
			velocity.y = -jumpVelocity;

			antigravTrue = !antigravTrue;


			gravity = antigrav;

			gravity = gravity;
			print ("its false");


		float targetVelocityX= input.x * moveSpeed;
		velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing,(controller.collisions.below)?accelerationTimeGrounded:accelerationTimeAirborne);
		velocity.y += gravity *Time.deltaTime;
		controller.Move(velocity * Time.deltaTime);

That’s because you’re setting back gravity equals to itself, so it’s value won’t change.

Let’s say gravity = 10 and antigrav = -10
After gravity = antigrav; both your values would be equal to -10 cause this line of code says “set gravity value to antigrav’s value”

Then you try to set it back with gravity = gravity; but that’s like saying “gravity = -10” as in the line before you set gravity to this value.

A quick solution would be to add a “currentGravity” value so you won’t overwrite the gravity variable