Disable RigidBody Gravity Temporarily C#

Viewed 316

Firstly I want to apologise as i understand this will be a very basic request, but I am very new to this world.

i just wish to disable the gravity element of my rigid body for a set amount of time and then enable it until the game resets. if I have understood what ive located on google I need to use a Coroutine but I am having issues doing so.

I attempted to set my gravity element to false initially and use a Wait For Seconds statement to set the gravity to true after so long, but this presented me with errors.

Any help would be greatly appreciated.

2 Answers
[SerializeField] private Rigidbody rb = null;
private Coroutine disbaledGravity = null;

public void DisableGravity(float timeToDisable)
{
     rb.useGravity = false;
     if(disabledGravity  != null)
          StopCoroutine(disabledGravity);

    disableGravity = StartCoroutine(EnableGravityAfterDelay(timeToDisable));
}

private IEnumerator EnableGravityAfterDelay(float delay)
{
     yield return new WaitForSeconds(delay);
     rb.useGravity = true;
     disableGravity = null;
}

Sorry if there are typos - on mobile. General idea is to call the public function with some amount of time where gravity should be disabled. In case a disable gravity event is already occurring, it is cleared and replaced with the new one. After the duration has elapsed after the disable gravity call, gravity is then re-enabled for the object. Once off mobile ill add some resource links to help with understanding the functions used.

The Rigidbody.useGravity boolean is exactly what you're looking for.

First, obtain a reference to the rigidbody whose gravity you wish to disable. For example via GetComponent:

private Rigidbody myRb;

public void Start()
{
    myRb = GetComponent<Rigidbody>();
}

Next, create a simple coroutine:

public IEnumerator GravityDisableRoutine()
{
    myRb.useGravity = false;
    yield return new WaitForSeconds(10); //You may change this number of seconds
    myRb.useGravity = true;
}

Now, whenever you want to disable the gravity, call:

StartCoroutine(GravityDisableRoutine());
Related