Apply gravity using C# in Unity

Hello programmers, In this article, I will show how to “Apply gravity using C# in Unity”

Adding gravity to the game object makes the experience of the game even better. Let’s get started with the building process.

Physics.Gravity

Unity game engine has built-in physics which is easy to use.

Gravity can be applied to all the game objects by adding the rigid body component to GameObject and enabling gravity.

Gravity can be enabled for an individual game object using its useGravity property.

On Earth’s surface, the gravity acceleration is approximately 9.8m/s/s

C# Script for Gravity in Unity

using UnityEngine;
using System.Collections;

public class GravityController : MonoBehaviour
{
    public Rigidbody rig;

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

    public void enable()
    {
        rig.useGravity = true;
    }

    public void disable()
    { 
        rig.useGravity = true; 
    }

}

Write the above code and attach this script to the required GameObject.

This script can enable or disable the gravity of the selected GameObject.

Leave a Reply

Your email address will not be published. Required fields are marked *