Search code examples
c#unity-game-enginecoroutinerigid-bodies

Disable RigidBody Gravity Temporarily C#


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.


Solution

  • 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());