How do I reference the default gravity value set in the inspector on my player's Rigidbody 2D?

I’m using a very basic script for climbing a ladder (see below), which switches off gravity and allows my player to climb up or down.

When the player exits the ladder (using OnTriggerExit2D), their gravity is returned to normal (in this case, a value of 10) using body.gravityScale = 10f;.

I would prefer this to return the player’s gravity to its ‘default’ value - as in, whatever it is is set as in the inspector. How can I reference that value here, instead of saying = 10f;? This seems like it should be simple, but I can’t find it anywhere/figure it out myself!

Thanks for your help.

private void FixedUpdate()

{

if (isClimbing)
{

body.gravityScale = 0;

body.velocity = new Vector2(body.velocity.x, vertical * speed);

}

else

{

body.gravityScale = 10f;

}

}

Store the value before you change it, and assign that value back afterwards.

If this is all happening in the same component, you can cache the value in a field in Awake/Start, and then have that as a point of reference for later.

2 Likes

Great, thank you.

In case its helpful to anyone else, here’s what I changed:

public class LadderMovement : MonoBehaviour
{

    private float defaultGravity;

void Start()
{
    defaultGravity = body.gravityScale;
}

private void FixedUpdate()
{
    if (isClimbing)
    {
        body.gravityScale = 0;
        body.velocity = new Vector2(body.velocity.x, vertical * speed);

    }
    else
    {
        body.gravityScale = defaultGravity;
    }
}
1 Like