How to change gravity scale in a script

I want to change the gravity scale when I click the jump(space key)

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform GFX;
    [SerializeField] private float jumpForce = 10f;
    [SerializeField] private LayerMask groundLayer;
    [SerializeField] private Transform feetPos;
    [SerializeField] private float groundDistance = 0.25f;
    [SerializeField] private float jumpTime = 0.3f;
    [SerializeField] private float gravity = 15f;
    //[SerializeField] private float crouchHeight = 0.2f;
    private bool isGrounded = false;
    private bool isJumping = false;
    private float jumpTimer;

    private void Update() {
        isGrounded = Physics2D.OverlapCircle(feetPos.position, groundDistance, groundLayer);

        if (isGrounded && Input.GetButtonDown("Jump")) {
            isJumping = true;
            jumpTimer = 0;
            rb.velocity = Vector2.up * jumpForce;
        }

        if (isJumping && Input.GetButton("Jump")) {
            if (jumpTimer < jumpTime) {
                rb.velocity = Vector2.up * jumpForce;
                jumpTimer += Time.deltaTime;
            } else {
                isJumping = false;
            }
        }

        if (Input.GetButtonUp("Jump")) {
            isJumping = false;
        }

*Code for the jump

What part are you struggling with?

The Unity documentation shows the location and spelling of the gravity scale property and it is used just like any other C# / Unity thing: you get a reference to the Rigidbody2D (which it looks like you already have) and use that.

Otherwise…

How to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, log output, variable values, and especially any errors you see
  • links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

I wan tit so this value can be changed whenever I click a key, for example if I click the space key it will change the value to -3 but if I like the up arrow it will change the value to 15

9910443--1432227--Screenshot 2024-06-26 205216.png

Based on the above, the parts you will need are:

  • how to read and process input (such as the space key)
  • how to get a reference to the Rigidbody2D
  • how to set the .gravityScale field according to your desires.

This is a great approach when you first start out:

Imphenzia: How Did I Learn To Make Games: